繁体   English   中英

如何确保 Observable.map 仅在成功时执行?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM