[英]Angular 2: http.get in Observable not handling error
I'm using observables for Http calls, which have been working fine, but then I changed up my controllers and noticed that my code apparently isn't handling errors. 我对Http调用使用了可观察的对象,该方法工作正常,但是后来我更换了控制器,并注意到我的代码显然没有处理错误。
Here is a look at the code from my service (SellingMenuService): 这是我的服务(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.
});
}
And here is the relevant code from my component: 这是我组件中的相关代码:
constructor(public sellingMenuService: SellingMenuService) { }
getVarietyList(): void {
this.sellingMenuService.getVarieties().subscribe(res => {
console.log(res);
this.varieties = res;
});
}
And here are some errors in my console: 这是我的控制台中的一些错误:
If I'm getting a 500 error, shouldn't those console logs from my service above get hit? 如果出现500错误,上面服务中的那些控制台日志是否不应该受到攻击? Why don't they?
他们为什么不呢?
You appear to have your error-handling logic inside map()
. 您似乎在
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')
);
See: How to catch exception correctly from http.request()? 请参阅: 如何从http.request()正确捕获异常?
You are trying to catch error in the map
method, while you should do it inside subscribe
. 您尝试在
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.
});
}
You can also add third parameter to observable. 您还可以在observable中添加第三个参数。 It will be resolved when observable is
finalized
: 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")
});
}
You can read more here: http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html 您可以在此处阅读更多信息: http : //reactivex.io/rxjs/class/es6/Observable.js~Observable.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.