Search code examples
angulartypescriptangular-http-interceptorsangular-httpclient

Angular interceptor, run code after the outgoing request is finished


I got a simple interceptor which checks if an outgoing request is to a specific endpoint type, in this case events and favoriteevents.

This almost works as expected. The one thing that it's doing wrong is that this.dispatcher dispatches before the outgoing request is completed.

How can I change it so that the outgoing request runs first and then the dispatch call is made?

import {Injectable, Injector, Optional} from '@angular/core';

import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor
} from '@angular/common/http';

import {Observable} from 'rxjs/Observable';

import {AppConstants} from '@constants/app-constants.constant';
import {DispatcherService} from '@services/dispatcher.service';

@Injectable()

export class EventsInterceptor implements HttpInterceptor {

  constructor(private dispatcher: DispatcherService) {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    const urls = [
      {requestType: 'PUT', snippet: '/events/'},
      {requestType: 'DELETE', snippet: '/events/'},
      {requestType: 'PUT', snippet: '/favoriteevents'},
      {requestType: 'DELETE', snippet: '/favoriteevents'}
    ];

    for (const url of urls) {

      if (req.method === url.requestType || url.requestType === null) {

        if (req.url.indexOf(url.snippet) !== -1) {
          this.dispatcher.dispatch({type: AppConstants.actions.refreshFavoriteEvents});
        }
      }
    }

    return next.handle(req);
  }
}

Solution

  • You can try something like

    ...
    return next.handle(req).pipe( tap( () => {
        if (someCondition) this.dispatcher.dispatch(...);
    }) );