Could someone provide a detailed explanation of exhaustMap in the context of Angular using rxjs?



import {
  HttpHandler,
  HttpInterceptor,
  HttpParams,
  HttpRequest,
} from '@angular/common/http';
import { Injectable } from '@core/services/auth.service';
import { exhaustMap, take } from 'rxjs/operators';
import { AuthenticationService } from './authentication.service';

@Injectable()
export class AuthInterceptorService implements HttpInterceptor {
  constructor(private authService: AuthenticationService) { }

  intercept(req: HttpRequest<any>, next: HttpHandler) {
    return this.authService.checkUser.pipe(
      take(1),
      exhaustMap((user) => {
        if (!user) {
          return next.handle(req);
        }
        const modifiedReq = req.clone({
          params: new HttpParams().set('auth', user!.token!),
        });

        return next.handle(modifiedReq);
      })
    );
  }
}


This specific file serves as an interceptor that adjusts the request URL by including 'auth' query parameters with a token value obtained from the user object. However, it may be challenging to comprehend the inner workings of the exhaustMap function.

Answer №1

exhaustMap is a type of higher order pipe operator that subscribes to the observable being piped and, for each emitted value, returns a new observable based on the function provided.

The key difference between exhaustMap, switchMap, concatMap, and mergeMap lies in how they handle scenarios where the mapped observable has not completed but a new value is emitted by the source observable.

In this specific case, exhaustMap is utilized. This means that if a new value is emitted from the source observable while the previously mapped observable is still active, the new value will be ignored until the ongoing operation completes.

Only after the previous operation finishes will new values from the source observable be processed by the inner observable once again.

Answer №2

Imagine a situation where this piece of code this.authService.emitUser is considered as the main source of data, also known as a source observable. If this source emits a user named Theri, and this data is being handled by an operation called exhaustMap, then no matter how many times the source observable emits additional users like Muthu, the exhaustMap will continue processing the initial user Theri until its task is completed. Only after finishing with Theri, will the operations move on to handle the new user Muthu.

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

Highlighting JavaScript code with React Syntax Highlighter exclusively

I've been struggling to highlight Ruby code, but it seems like no matter what I do, it keeps highlighting JavaScript instead. It's frustrating because I can't seem to get it right. import React from "react"; import atom from "node_module ...

Angular 2- Custom input forms sourced from various components for enhanced user experience

I am currently working on creating an angular 2 form using template-driven and I want to reuse a custom input that I have created. My main component structure looks like this: <form (ngSubmit)="onSubmit(f.value)" #f="ngForm"> <custom-in ...

Not adhering to directive scope when transclusion is used, despite explicit instructions to do so

Trying to use a transcluding directive within another controller, but the inner scope isn't being redefined as expected. Despite trying different methods, I can't seem to figure out what's going wrong. The simplified code looks like this: ...

AngularJS ng-repeat: displaying a list of filtered outcomes exclusively

I currently have a ng repeat that loops through a set of results. <a class="list-group-item" href="#trip/{{trip.id}}/overview" ng-repeat="trip in trips | filter:search | limitTo:-15"> Basically, as I enter more text into my input field, the list sh ...

What sets apart AngularJs's complete $http post from its shorthand counterpart $http.post?

When sending Object data from app.js to homecontroller using two different methods (full $http.post and shorthand $http.post) as shown below: var book = { "title" : $scope.addTitle, "publisher" : $scope.publisherSelected[0], "authors" : $scope ...

The size of the search input and textarea in HTML decreases when viewed on an iPad device

Currently utilizing Bootstrap 3 and AngularJs for this project. Implementing the following markup for the input field with type 'search': <input type="search" class="form-control" id='roomSearch' placeholder="Search" ng-model=&apo ...

Utilizing Lodash efficiently with tree shaking

After experimenting with using lodash functions as a specific import versus as a destructured object, I noticed a significant difference in file size. When imported as shown below, the size is only 14.7KB. However, when I tried importing as a destructured ...

Tips for simulating or monitoring an external function without an object using Typescript 2 and Jasmine 2 within an Angular 4 application

In order to verify if a function called haveBeenCalledWith() includes the necessary parameters, I am seeking to validate the correctness of my call without actually executing the real methods. I have experimented with multiple solutions sourced from vario ...

What's the best way to refresh append() functionality within a modal? I'm currently working with NODE JS and AJAX and

Whenever I click the modal, the append() calls are adding HTML content. But if I try to use empty() or html(), the modal stops appearing altogether. What is the correct approach to creating this modal? function loadModalContent(id) { $('#myModal& ...

I am having trouble getting Google Maps to load

Why does the map on my website only load when the browser window is resized? Below is the JavaScript code being used: <div class="map-cont"> <div id="map" class="location-container map-padding" style="width:100%;height:400px;background:y ...

What is the best way to initialize React-map-gl with the user's current location as the default latitude and longitude?

Is there a way to render the map with default values of viewport set to user's location without needing to click a locate me button? <ReactMapGL mapboxApiAccessToken={mapboxApiKey} mapStyle="mapbox://styles/mapbox/streets-v11" ...

What is the definition of reusable components within the context of Angular, React, and Vue?

I've been hearing a lot about reusable components. What does this actually mean? For instance, if I want to showcase basic user information like ID, name, age, etc. Does it imply that the component is "plug and play," where you simply write the sele ...

Issue with Angular ngModel not syncing with variable changes

Currently using Angular 4 and Typescript, I have a table containing <select> elements in my template: <tr *ngFor="let task of tasksDetails"> <td>{{task.name}}</td> <td> <select class="form-control" [(ngMode ...

What is the best way to showcase several items in a slide with Ionic 2?

I am a beginner with Ionic 2 and I am trying to display multiple products in a single slide. While I have successfully displayed the slide, I am seeing small dots below the image. How can I remove these dots? Below is my HTML code: <ion-row class="bran ...

Is there a way to upload multiple files using expressjs?

I'm looking for a way to efficiently send multiple files, including an entire directory, so that I can access them in another JavaScript file called from an HTML file. const app = require("express")(); const http = require("http"). ...

Submitting late leads to several consecutive submissions

I am working on a jQuery code that aims to introduce a short time delay to allow for the proper execution of an AJAX request: $('#form_id').submit(function(e) { e.preventDefault(); $submit_url = $(this).data('submitUrl'); ...

Creating an interactive time selection tool with two dropdown lists that are dependent on each other using HTML and JavaScript

Hi everyone, I am new to JavaScript. I am currently working on creating two dropdown lists, one for 'Start Time' and another for 'End Time'. These dropdown lists will display hours in a 24-hour format with intervals of 30 minutes. In t ...

By utilizing .focus() in iOS8, the virtual keyboard will be displayed and the page will automatically scroll upon touch

In the era before iOS8, when utilizing the Javascript .focus() method on an input element, it seemed as though nothing happened - the virtual keyboard did not make an appearance. However, with the latest iOS 8 update, executing the .focus() method initiall ...

How to access a variable in an Angular Factory's callback function from outside the factory

Here's a look at the structure of My Factory: .factory('MyFactory', function(){ return: { someFunction: functon(firstParam, secondParam, resultObject) { $http.get(url).success(resultObject); } ...

Creating a state in React and populating the rows of a Material-UI table with fixed data

I have implemented a table in the UI using the material-UI Table component. Initially, I added static data without using the state property of react. Now, I am looking for a way to assign static data to table rows by utilizing the state property. The code ...