Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2: Subscribe to all HTTP requests

Tags:

angular

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!

like image 392
Vingtoft Avatar asked Jun 06 '26 01:06

Vingtoft


1 Answers

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

like image 73
Günter Zöchbauer Avatar answered Jun 07 '26 20:06

Günter Zöchbauer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!