I'm building a webapp using Angular2.
Is it possible to execute a function each time Angular2 makes a HTTP request?
This will be used for checking if the JWT token needs to be refreshed.
Thanks!
You can use a custom Http
class that provides an observable that components or other services can subscribe to and that emits an event every time a request is made
@Injectable()
class NotifyingHttp extends Http {
requestSent:Subject = new Subject();
requestCompleted:Subject = new Subject();
constructor(_backend: ConnectionBackend, _defaultOptions: RequestOptions) {
super(_backend, _defaultOptions);
}
get(url: string, options?: RequestOptionsArgs) : Observable<Response> {
this.requestSent.next(url);
return super.get(newUrl, options)
.finally(response => this.requestCompleted.next(url));
}
post(...)
...
}
Each method needs to be overridden this way (get, post, ...)
You can create a shared module that is then activated by adding it to imports of AppModule
:
@NgModule({
imports: [HttpModule],
export: [HttpModule],
providers: [
{provide: ConnectionBackend: useClass XhrBackend},
{provide: Http, useClass: NotifyingHttp}]
})
export class NotifyingHttpModule {}
@NgModule({
imports: [BrowserModule, NotifyingHttpModule],
declarations: [AppModule],
bootstrap: [AppModule]
})
export class AppModule {}
See also Angular2 : The responses to HTTP get requests are being cached in IE