[英]Angular2: strange vague error when trying to get Json from server using a rest service
[英]get response error from rest api using angular2
Client.service.ts:
add(client: Client): Observable<Client> {
return this.authHttp.post(this.URI, client)
.map((res) => res.json()
//...errors if any
,(message)=>message.json());
Client.add.componement.ts:
this.clientService.add(client)
.subscribe(_client => {
this.onAdd.emit(_client);
},
message => console.log("THIS ERROR"+message));
我如何獲得消息或錯誤列表, 導致我在瀏覽器中得到結果
如果將angular2-jwt用作authHttp
確保將其導入並正確注入服務中:
import { AuthHttp } from 'angular2-jwt';
-> constructor (private authHttp: AuthHttp) { }
然后,您可以執行類似操作(確保將內容類型/請求選項添加到POST請求中):
add(client: Client): Observable<Client> {
let headers = new Headers({ 'Content-Type': 'application/json' }); // set content-type
let options = new RequestOptions({ headers: headers }); // create a request option
return this.authHttp.post(this.URI, client, options)
.map((res) => res.json())
//...errors if any
.catch(this.handleErrorObservable);
}
private handleErrorObservable(error: Response | any) {
console.error(error.message || error);
return Observable.throw(error.message || error);
}
然后,當您調用它時:
this._clientService.add(client)
.subscribe(
res => console.log(res),
err => console.log(err)
);
否則,請確保在Web API代碼中以JSON格式返回所需的響應。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.