[英]How to make sure that the Observable.map only executed on succes?
I just want to make sure that code inside map
function should be called only on success but not on failure.我只是想确保
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;
});
}
I don't know whether the code inside map
executes only on success or not.我不知道
map
的代码是否只在成功时执行。 And also, I have to return an Observable
so , I can't apply subscribe
function here.而且,我必须返回一个
Observable
所以,我不能在这里应用subscribe
功能。
Observable#map
operator will be executed on success response only (eg status 200). Observable#map
操作符将仅在成功响应时执行(例如状态 200)。 Observable#catch
operator is intended to catch failures. Observable#catch
运算符旨在捕获故障。
Also, Observable#catch
operator will catch javascript errors thrown while mapping success response as well.此外,
Observable#catch
操作符也将捕获映射成功响应时抛出的 javascript 错误。 Example:例子:
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!');
}
});
}
Subscribe block:订阅块:
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.