我正在使用可观察的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错误,那么上述我的服务中的控制台日志是否应该被点击?他们为什么不呢?
答案 0 :(得分:1)
您似乎在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')
);
答案 1 :(得分:1)
您试图在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