[英]How to make sure that the Observable.map only executed on succes?
我只是想确保map
函数中的代码应该只在成功时调用,而不是在失败时调用。
delete(department: Department): Observable<Department[]> {
return this.post('/delete', body).map(response => {
let index: number = this.departments.indexOf(department);
if (index > -1) {
this.departments.splice(index, 1);
}
return this.departments;
});
}
我不知道map
的代码是否只在成功时执行。 而且,我必须返回一个Observable
所以,我不能在这里应用subscribe
功能。
Observable#map
操作符将仅在成功响应时执行(例如状态 200)。 Observable#catch
运算符旨在捕获故障。
此外, Observable#catch
操作符也将捕获映射成功响应时抛出的 javascript 错误。 例子:
fetchDashboardData(): Observable<Dashboard> {
return this._http.get(reqUrl, reqOptions)
.map((response: Response) => new Dashboard(response.json().items[0].dashboard))
.catch((error: any) => {
if (error instanceof Error) {
// js error, e.g. response.json().items was an empty array
console.log(error); // => “Cannot read property 'dashboard' of undefined...
return Observable.throw('Incomplete response data!');
} else {
return Observable.throw('Server error!');
}
});
}
订阅块:
this.dashboardService.fetchDashboardData().subscribe(
(dashboard: Dashboard) => {
this.dashboard = dashboard;
console.log('Success fetching dashboard data!', dashboard);
},
(errMssg: string) => {
console.error(errMssg); // => 'Incomplete response data!'
// or 'Server error!'
},
() => {
// finally block!
}
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.