Angular 2 - How to get Observable.throw globally

2020-02-06 09:04发布

问题:

How, I want to handle http errors (specially status 401) globally. I know I can do something like that

getCompanies() {
    return this.http.get('https://angular2.apispark.net/v1/companies/')
       .map(res => res.json())
       .catch(res => {
           return Observable.throw(res.json());
       });

How can I get this error on another component?

Just to explain I want to implement that all 401 erros redirect the user to login page

回答1:

An approach could be to extend the HTTP object to intercept errors:

@Injectable()
export class CustomHttp extends Http {
  constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) {
    super(backend, defaultOptions);
  }

  request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
    console.log('request...');
    return super.request(url, options).catch(res => {
      // do something
    });        
  }

  get(url: string, options?: RequestOptionsArgs): Observable<Response> {
    console.log('get...');
    return super.get(url, options).catch(res => {
      // do something
    });
  }
}

and register it as described below:

bootstrap(AppComponent, [HTTP_PROVIDERS,
    new Provider(Http, {
      useFactory: (backend: XHRBackend, defaultOptions: RequestOptions) => new CustomHttp(backend, defaultOptions),
      deps: [XHRBackend, RequestOptions]
  })
]);

If 401 errors occur as this level, you could redirect the user to login page based on the current router you injected on this CustomHttp class.



标签: angular rxjs