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

The act of employing `Function.prototype.run` within an Angular TypeScript class is deemed as illegitimate

Is there a way to globally define a new function called run within my Angular component as shown below? Function.prototype.run = function (delay: number) { // some content; }; However, the compiler shows an error that the Property 'run' does n ...

The ngModel in Angular 6 did not update the value within the app component

Currently, I am honing my skills in Angular and TypeScript but have encountered a minor issue. Below is the code snippet from my component.html <div> <input [(ngModel)]="mynumber"> N is now {{N}} // some content I want to do with ...

The conversion of a newline in an Angular page is done using &lt;br/&gt tag

Here is a function I have: setLocalVariableOnAccepted(ogp, hb, responseJson) { if (responseJson.ofgp === undefined) { this.ogpStatus = 'orange'; this.ogpStatusMsg = responseJson.ofgp + ', <br/> No change. Previous va ...

Passing arguments from nodes in Angular 2

I am looking to pass a parameter from a node, rather than a property. Here is an example of what I want: <!-- I want to use this: --> <navbar-comp> <items> <item label="Page 1" path="/page1" /> <item label="Page 2" pat ...

Is there a way to adjust the background color of the clicked tab with divs and revert the others back to their original color?

<span class="row top-bar-left align-items-center" style="width: 80%; float:left"> <div tabindex="1" class="link tab" routerLink="details" routerLinkActive="active" [qu ...

Using React hooks with Material-UI: Snackbar displaying only on first occasion and not again

I have identified an issue that can be easily reproduced. Steps to replicate: Step 1: Start a react app and include material-ui in the project: prompt> create-react-app mui-test prompt> cd mui-test prompt> yarn add @material-ui/core @material-ui ...

Deactivating Google Map Clustering for Individual Markers

I'm currently utilizing Angular 4, Google Maps v3, and Marker Clusterer v2 - all of which are the latest versions. I'm attempting to implement a straightforward example found in the official Google Maps documentation (https://developers.google.co ...

Can you explain the meaning and significance of the @Injectable annotation?

Is the use of @Injectable indicating that we are able to inject MyService into other classes, or does it mean that we can inject other classes into MyService? @Injectable({ providedIn: 'root' }) export class MyService { constructor() { } } ...

Configuring Typescript target and library to utilize Promise.allSettled on outdated web browsers

I am currently using TypeScript version 4.3.5 and Node.js version 14.18.1 in my project. The code I am working on is compiled to target both old and new browsers by setting target=es5 in the tsconfig file. I make use of both Promise.all and Promise.allSett ...

Encountering compilation errors with TypeScript files in Angular 2 while using Visual Studio 2017

Currently, I am in the process of developing an Angular 2 application Here is a snippet of the TypeScript code that I have written: import { Component } from 'angular2/core'; @Component({ selector: 'my-app', template: ' &l ...

Issue C2039: 'IsNearDeath' cannot be found within 'Nan::Persistent<v8::Object,v8 ::NonCopyablePersistentTraits<T>>'

After updating my nodejs to v12.3.1, I encountered errors when attempting to execute npm install in my project directory. error C2059: syntax error: ')' (compiling source file ..\src\custo m_importer_bridge.cpp) error C2660: 'v8 ...

What is the best way to handle typing arguments with different object types in TypeScript?

Currently, I have a function that generates input fields dynamically based on data received from the backend. To ensure proper typing, I've defined interfaces for each type of input field: interface TPField { // CRM id as a hash. id: string nam ...

What is the process for exporting libraries in TypeScript?

Encountering an error when attempting to export socket.io using this method import socketIOClient from 'socket.io-client';. The error message is TS1192: Module '"***/node_modules/socket.io-client/build/index"' has no default e ...

The present URL of Next.js version 13

When working with Next.js App Router in SSR, how can I retrieve the complete URL of the current page? I am unable to use window.location.href due to the absence of a defined window object, and using useRouter() does not provide access to the full URL. ...

Utilize Angular to transform items in a nested array into comma-delimited values prior to assigning them to a grid

Here is an excerpt from a JSON response retrieved from an API: { "totalCount": 2, "customAttributes": [ { "objectType": "OWNER", "atrributeId" ...

Searching for a way to access the HTTP request header using ReactJS?

Can anyone assist me in retrieving the request header's cookie? I have searched extensively but haven't found a satisfactory document. Please share with me a reliable solution. ...

List out all the classes that implement an interface in Typescript

Greetings to all TypeScript enthusiasts! Here's a challenge I want to tackle: I aim to establish an interface -- let's name it IShape -- and define several classes (Rectangle, Circle, Triangle) that adhere to the IShape interface. Let's sa ...

Unable to get md-virtual-repeat to work within md-select?

Attempting to use md-select to showcase a large amount of data is causing the browser to freeze upon opening. To address this, I tried implementing md-virtual repeat within md-select for improved performance. However, the code doesn't seem to be funct ...

How can I use JavaScript to sort through an array and organize the data into groups?

Below is an array that I currently have: Status=["active","inactive","pending","active","completed","cancelled","active","completed"] I am looking to achieve the following result: StatusInfo=["active":3,"inactive":2,"pending":1, "completed":2, "cancelle ...

Comprehending the concepts of Observables, Promises, using "this" keyword, and transferring data within Angular with TypeScript

I am trying to figure out why I keep receiving the error message: "Uncaught (in promise): TypeError: this.dealership is undefined" when working with the authentication.service.ts file. export class AuthenticationService { private currentUserSubject: ...