Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

Why does finally() not work after catching on an Observable in Angular 2?

I am trying to add a loading spinner to every request that ends in Angular 2, so I extended the Http service calling it HttpService. After every request I would like to call a finally() function after catching errors so that I can stop the loading spinner.

But typescript says:

[ts] Property 'finally' does not exist on type 'Observable'.

import { AuthService } from './../../auth/auth.service';
import { Injectable } from '@angular/core';
import { Http, XHRBackend, RequestOptions, RequestOptionsArgs, Request, Response, Headers } from '@angular/http';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

@Injectable()
export class HttpService extends Http {

    constructor(
        backend: XHRBackend,
        options: RequestOptions,
        private authservice: AuthService
    ) {
        super(backend, options);
        this.updateHeaders(options.headers);
    }

    request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> {
        return super.request(url, options)
            .catch((response: Response) => this.authError(response))
            .finally(() => {
                // ...
                /* Do something here when request is done. For example
                finish a spinning loader. */
            });
    }

    private authError(response: Response) {
        if (response.status === 401 || response.status === 403) {
            this.authservice.logout();
        }
        return Observable.throw(response);
    }

    private updateHeaders(headers: Headers) {
        headers.set('Content-Type', 'application/json');
        if (this.authservice.isloggedIn()) {
            headers.set('Authorization', `Bearer ${this.authservice.getToken()}`);
        }        
    }
}

How can I run some code after every http request like this? What is the best way of doing it?

question from:https://stackoverflow.com/questions/43876283/why-does-finally-not-work-after-catching-on-an-observable-in-angular-2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You forgot to import it:

import 'rxjs/add/operator/finally';

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...