簡體   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