Angular interceptor allows the execution of code after the outgoing request has completed its process

In the process of creating a simple interceptor, I have encountered an issue. The interceptor is designed to check if an outgoing request is targeting a specific endpoint type, namely events and favoriteevents.

While the interceptor works almost as intended, there is one issue that needs to be addressed. Currently, the this.dispatcher dispatches before the outgoing request is completed.

How can I modify the code so that the outgoing request executes first, followed by the dispatch call?

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);
  }
}

Answer №1

If you want to experiment, consider the following approach

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting: Issue with Angular 2 bidirectional data binding on two input fields

Hi there, I am encountering an issue with the following code snippet: <input type="radio" value="{{commencementDate.value}}" id="bankCommencementDateSelect" formControlName="bankCommencementDate"> <input #commencementDate id="bankCommencementDat ...

What is the process for inferring generic return values in TypeScript methods?

I'm curious about how TypeScript infers return types with generics. When a method that uses a generic type as its return value is called without specifying a generic type parameter, how does TypeScript infer the return type? I know that a generic type ...

Unlock the contents of a directory using a .htaccess file

My directory setup looks something like this: www.examplelink.com/angular/dist/my-app. I need to reach this directory when going to the link : www.examplelink.com/angular. What would be the best way to achieve this using htaccess? ...

Show a notification if the search bar returns no results

I am facing an issue with my search functionality. When a user searches for something not in the list, an error message should be displayed. However, in my case, if I search for "panadol" in my list, it displays the list containing that word and shows an e ...

Identifying Classifications Based on Input Parameters

I'm encountering some difficulty in typing a function that calls an external API and returns data based on the parameters sent. Here is what I have so far... import axios from 'axios'; interface IGetContactArgs { properties?: string[]; } ...

Developing a Next.js application using Typescript can become problematic when attempting to build an asynchronous homepage that fetches query string values

Having recently started delving into the world of React, Next.js, and Typescript, I must apologize in advance if my terminology is not entirely accurate... My current learning project involves creating an app to track when songs are performed. Within the ...

Unable to Trigger Click Event on Div Element in Angular 9

Take a look at my HTML code snippet <mat-grid-list cols="3" rowHeight="150px"> <mat-grid-tile *ngFor="let tile of tiles;index as j;" [colspan]="tile.cols" [rowspan]="tile.rows" ...

What is the most effective way to determine the data type of a variable?

My search skills may have failed me in finding the answer to this question, so any guidance towards relevant documentation would be appreciated! I am currently working on enabling strict type checking in an existing TypeScript project. One issue I'v ...

Parent and router-outlet in Angular 4 fashion

Suppose we are presented with the following code: <div class="container"> <div class="row"> <div class="col-sm-4 col-md-3"> <app-sidebar></app-sidebar> </div> <div class="c ...

What is the best way to update queryParams without activating subscribe functions?

Hello, I am currently in the process of developing an angular app with multiple routes. When navigating to a specific page, the queryParams trigger the subscribe function. While on the page, I need to be able to change the queryParams without triggering ...

Exploring the world of dynamic form creation using Angular and Mat-select options

I'm working on an Angular application and I want to create a dynamic form using Mat-select for the type selection. Depending on the chosen type, I need to be able to add or remove fields dynamically. I also want to display a specific field if the typ ...

Start incrementing from the value of x

I'm trying to create an incremental column in Node.js with TypeORM, similar to this: @Column() @Generated('increment') public orderNumber: number; Is there a method to set TypeORM to begin counting from 9000 instead of the default starting ...

What is the best way to prevent a font awesome icon from appearing in a span during data loading

I am currently working on an Angular 11 application where I have implemented an icon to trigger the loading of a graph. However, I have noticed that there is a delay in loading the graph when the icon is clicked. To prevent users from triggering the icon m ...

Angular 4: Retrieving the selected element's object from a collection of elements

In my x.component.html file, I have a list of objects that are being displayed in Bootstrap cards like this: <div *ngFor="let item of items | async"> <div class="row"> <div class="col-lg-6"> <div class="card ...

Issue encountered when attempting to install dialog-polyfill for IE11 in Angular2

Currently, I am facing issues with getting dialogs to function properly on Internet Explorer 11. It seems that in order to make it work, I need to install a polyfill. However, my attempts to install the polyfill using npm have resulted in numerous errors t ...

How do I add a new item to an object using Ionic 2?

example item: this.advData = { 'title': this.addAdvS2.value.title , 'breadcrumb': this.suggestData.breadcrumb, 'price': this.addAdvS2.value.price ...

What is the best way to dynamically assign formControlNames in Angular using *ngFor?

I am currently facing a challenge with setting form controls using *ngFor over objects in an Array. The number of objects in the array can vary, sometimes resulting in only 1 object while other times multiple objects are present. My specific issue revolve ...

The issue arises when attempting to call a method from the same service within jsPDF in an Angular environment

Below you will find my Angular project's pdfService. I am facing an issue where calling the this.formatter() method inside myPDF is not functioning properly. export class pdfService { formatter(value: number): string { return new Intl.N ...

The installation of Clarity through the command 'ng add @clr/angular' does not succeed

Following the guidance in 'Chapter 3: Building an Issue Tracking System using Reactive Forms' from Angular Projects: Discover Angular 12 with 10 innovative projects and cutting-edge technologies, 2nd Ed. by Aristeidis Bampakos. This chapter&apos ...

Angular 4 is having trouble retrieving the JSON response

When I attempt to log errors in a specific scenario and use error, the following error message is displayed: { "errors" : [ { "entity" : "Movement", "property" : "direction", "invalidValue" : null, "message" : "Il campo non può essere v ...