Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - How to get Observable.throw globally

Tags:

angular

rxjs

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

like image 612
Gustavo Lira Avatar asked Feb 08 '23 17:02

Gustavo Lira


1 Answers

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.

like image 102
Thierry Templier Avatar answered Feb 10 '23 07:02

Thierry Templier