![](/img/trans.png)
[英]Angular 2 : Get 404 error in http.get call with Observable return
[英]Angular 2: http.get in Observable not handling error
我對Http調用使用了可觀察的對象,該方法工作正常,但是后來我更換了控制器,並注意到我的代碼顯然沒有處理錯誤。
這是我的服務(SellingMenuService)中的代碼:
public getVarieties(): Observable<any> {
return this.http.get(this.varietyListUrl).map(response => {
return response.json();
}, (error: any) => {
console.log(error);
console.log('error finding variety list');
// TODO: implement error handling here.
});
}
這是我組件中的相關代碼:
constructor(public sellingMenuService: SellingMenuService) { }
getVarietyList(): void {
this.sellingMenuService.getVarieties().subscribe(res => {
console.log(res);
this.varieties = res;
});
}
如果出現500錯誤,上面服務中的那些控制台日志是否不應該受到攻擊? 他們為什么不呢?
您似乎在map()
有錯誤處理邏輯。
import 'rxjs/add/operator/catch';
return this.http.request(request)
.map(res => res.json())
.subscribe(
data => console.log(data),
err => console.log(err),
() => console.log('yay')
);
您嘗試在map
方法中捕獲錯誤,而應該在subscribe
。
public getVarieties(): Observable<any> {
return this.http.get(this.varietyListUrl).map(response => {
return response.json();
}).subscribe((res: any) => {
console.log(res);
}, (error: any) => {
console.log(error);
console.log('error finding variety list');
// TODO: implement error handling here.
});
}
您還可以在observable中添加第三個參數。 finalized
可觀察性時將解決此問題:
public getVarieties(): Observable<any> {
return this.http.get(this.varietyListUrl).map(response => {
return response.json();
}).subscribe((res: any) => {
console.log(res);
}, (error: any) => {
console.log(error);
console.log('error finding variety list');
// TODO: implement error handling here.
}, () => {
console.log("finalized")
});
}
您可以在此處閱讀更多信息: http : //reactivex.io/rxjs/class/es6/Observable.js~Observable.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.