3

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!

Vingtoft
  • 13,368
  • 23
  • 86
  • 135

1 Answers1

5

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

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • You need to use a factory. Extending Http Still causes the Http constructor to be called by Angular, instead of the custom class constructor ([related to this](http://stackoverflow.com/a/40295956/2587435)). So you need to use a factory and create it yourself. And since ConnectionBackend is an interface (no provider for that token), you need to use XHRBackend for the factory. – Paul Samsotha Dec 07 '16 at 17:47
  • That might explain why I hadd to add a provider `{provide: ConnectionBackend: useClass XhrBackend}`, but that should do (according to a test in a plunker I recently made) – Günter Zöchbauer Dec 07 '16 at 17:48