Angular 2 - How to get Observable.throw globally

前端 未结 1 651
醉话见心
醉话见心 2020-12-11 08:46

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://an         


        
1条回答
  •  無奈伤痛
    2020-12-11 09:21

    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 {
        console.log('request...');
        return super.request(url, options).catch(res => {
          // do something
        });        
      }
    
      get(url: string, options?: RequestOptionsArgs): Observable {
        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.

    0 讨论(0)
提交回复
热议问题