我只是想确保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
功能。
答案 0 :(得分:1)
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!
}
);