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?
Asked
Active
Viewed 755 times
0
-
Looks like a dup of http://stackoverflow.com/questions/35498456/what-is-httpinterceptor-equivalent-in-angular2/35499034#35499034 – Günter Zöchbauer Apr 01 '16 at 07:23
1 Answers
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