2016-01-22 45 views
9

這是我第一次使用angular 2.我創建了一個簡單的表單並嘗試提交它,但是當http.post被執行時什麼也沒有發生。在網絡選項卡中沒有請求,沒有錯誤。angular2:http post不執行

這裏是我的代碼:

save(model) { 
     var uri = this._baseUri + "/api/contact/AddContact"; 

     let md = JSON.stringify(model); 

     this.http.post(uri, 
      JSON.stringify(md), 
      { 
       headers: new Headers({ 
        'Content-Type': 'application/json' 
       }) 
      }) 
      .map(res => res.json()); 


    } 

我已經設置保存方法中設置斷點,並正在經歷什麼。但我說什麼也不會發生。我錯過了什麼?

回答

28

Observable是懶惰的,所以你需要訂閱它們來使請求執行,即使你不想處理響應。

類似的東西:

save(model) { 
    var uri = this._baseUri + "/api/contact/AddContact"; 
    let md = JSON.stringify(model); 

    this.http.post(uri, 
    JSON.stringify(md), 
    { 
     headers: new Headers({ 
     'Content-Type': 'application/json' 
     }) 
    }) 
    .map(res => res.json()).subscribe(); 
    } 

希望它可以幫助你, 蒂埃裏

+2

觀測量真厲害;-)你可以從這裏開始就反應式編程:https://gist.github.com/ staltz/868e7e9bc2a7b8c1f754。真的很有幫助,看到他們的力量 –

+0

非常感謝!爲什麼我以前沒有找到這篇文章。浪費了幾天的時間。乾杯 – Aashish