2016-08-24 55 views
1

我正在創建一個angular2應用程序,在該應用程序中,我在我的服務中使用http使POST致電mongoDBangular2-rc1 http.post無法正常工作

當我第一次進行POST調用時,它正常工作正常,即入口被正確插入到數據庫中,但是當我第二次發送數據時,它沒有被插入。

如果我第一次插入後重新加載頁面,那麼它的工作正常。

我做了一些調試,發現在第二次請求期間我的req.body是空白的。

這裏是我的代碼:

savePage(page: Object) { 
    this.headers.append('Content-Type', 'application/json'); 
    let url = this.baseUrl+'/pm/pages/';  
    let data={}; 
    data["data"]=page; 
    console.log(data); //this is printing both times correctly 
    //on second request data is blank where as it works correctly for first time  
    return this.http.post(url, JSON.stringify(data),{headers: this.headers}) 
     .map((res: Response) => res.json()).catch(this.handleError); 
} 

這裏是節點服務顯示我的req.body數據

page.service.ts。

第一次請求

body:{ 
    data:{ 
     name: 'wtwetwet', 
     desc: 'wetwetwetetwte', 
     isPublic: true, 
     createdBy: 'Bhushan' 
    } 
} 

第二請求

body: {} 

任何投入?

+0

什麼瀏覽器? 。 –

+0

Google Chrome版本52.0.2743.116 m(64位)..是瀏覽器的問題嗎? –

+0

我想不是。不知道什麼會導致這個問題。 –

回答

1

我終於意識到,我的方法用於設置內容類型,每次它被調用。

savePage(page: Object) { 
    this.headers.append('Content-Type', 'application/json'); 
    let url = this.baseUrl+'/pm/pages/';  
    let data={}; 
    data["data"]=page;   
    return this.http.post(url, JSON.stringify(data),{headers: this.headers}) 
    .map((res: Response) => res.json()).catch(this.handleError); 
} 

到:

因此更改代碼

savePage(page: Object) { 
    this.headers=new Headers(); 
    this.headers.append('Content-Type', 'application/json'); 
    let url = this.baseUrl+'/pm/pages/';  
    let data={}; 
    data["data"]=page;    
    return this.http.post(url, JSON.stringify(data),{headers: this.headers}) 
    .map((res: Response) => res.json()).catch(this.handleError); 
} 

奏效了我。 實際上,我們只需要在設置標頭時設置一次,但在我的代碼中已經設置好了,因此創建了新的Headers Object幫助我清除了以前設置的任何配置。

感謝您的幫助球員。

+0

我得到相同的錯誤,但已經設置標題只有一次。我正在使用rc4。任何想法? – Kishori

2

它看起來更像是一個後端的東西。然而,你應該包括在這個http調用中訂閱的代碼。

順便說一句,你爲什麼使用RC1? Angular 2現在在RC5上。

+0

我同意Billias關於這個問題的兩點意見。 –