2017-09-08 31 views
0

我打算使用HttpClient發佈到我的getFeedback終端並獲取響應並在我的應用中顯示它。 我有一個codeService和一個儀表盤組件,這是在我的代碼服務崗位代碼:Angular HttpClient無法獲得響應正文消息

 //method 1 
async generateFeedbackPost() { 
     var headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded'); 
     var body = new URLSearchParams(); 
     body.set('code', this.code); 
     return this.http.post(this.url, body.toString(), { headers }).toPromise(); 
    } 
    //method 2 
generateFeedbackPost2() { 
    var headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded'); 
    var body = new URLSearchParams(); 
    body.set('code', this.code); 
    return this.http.post(url, body.toString(), {headers}); 
} 

在我的儀表板組件我調用這些方法:

this.codeService.generateFeedbackPost2().subscribe(data => {console.log(data);}); 
this.codeService.generateFeedbackPost().then(data => {console.log(data);}); 

我已經嘗試了這兩種方式但是,它們都在控制檯中打印出null。然而,在我的Chrome開發者工具的網絡選項卡,我可以準確地看到的結果:

enter image description here

你知道如何檢索這些消息回來?

+0

是什麼'的console.log(JSON.stringify(數據))'的結果呢? – mok

+0

兩者都返回null –

+0

這可能是一個錯誤。請檢查您使用的網站的域名和api是否相同。 – TheChetan

回答

1

您收到錯誤消息,因此您無法看到data,在請求成功的情況下將顯示該錯誤。

爲了看結果,誤差在這種情況下,你可以使用這個:

this.codeService.generateFeedbackPost2().subscribe(
    data => {console.log(data);}, 
    error => console.log(error)); 
+0

我已經弄明白了,我犯了一個錯誤:在我的web服務部分,我忘了將結果更改爲json,我只是直接返回字符串。你的JSON.stringfy提醒我。在我修好那部分之後,兩種方法都可以工作!我試着添加這個錯誤部分,它也會打印出一些有用的消息,也稱json無法解析字符串。感謝您的幫助! –

+0

@JudahFlynn我很高興它有幫助。 – mok