0

Hi I want to handle a global 401 error after an http request with angular2. I want to extend BaseResponseOptions class. This is the corret way?

Marco Moretti
  • 689
  • 4
  • 11

1 Answers1

1

You could extend rather the Http class itself to handle such error globally. This way you will be able to leverage the catch operator on the underlying requests and catch 401 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]
  })
]);

Using only response options you won't be able to intercept requests / responses.

Thierry Templier
  • 198,364
  • 44
  • 396
  • 360