简体   繁体   中英

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.

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. And also, I have to return an Observable so , I can't apply subscribe function here.

Observable#map operator will be executed on success response only (eg status 200). Observable#catch operator is intended to catch failures.

Also, Observable#catch operator will catch javascript errors thrown while mapping success response as well. 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!
        }
    );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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