As @Günter pointed it out, there is no way to register interceptors. You need to extend the Http
class and put your interception processing around HTTP calls
First you could create a class that extends the Http
:
@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]
})
]);
The request
and requestError
kinds could be added before calling the target methods.
For the response
one, you need to plug some asynchronous processing into the existing processing chain. This depends on your need but you can use operators (like flatMap
) of Observable.
Finally for the responseError
one, you need to call the catch
operator on the target call. This way you will be notified when an error occurs in the response.
This links could help you: