Angular HttpInterceptor failing to trigger with nested Observables

Utilizing a HttpInterceptor is essential for adding my Bearer token to all calls made to my WebApi. The interceptor seamlessly functions with all basic service calls.

However, there is one specific instance where I must invoke 2 methods and utilize the results from both to construct a combined model. Despite attempting to nest the observables using MergeMap, ForkJoin, and FlatMap, none of these approaches seem to activate my HttpInterceptor...

A snippet of the interceptor code:

export class JwtInterceptor implements HttpInterceptor {

    constructor(private userService: UserService) { }

    public intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        // logic for adding authorization header with jwt token if available
        let currentUser = this.userService.getCurrentUser();
        if (currentUser && currentUser.token) {
            request = request.clone({
                setHeaders: {
                    Authorization: `Bearer ${currentUser.token}`
                }
            });
        }

        return next.handle(request);
    }
}

Description of the service calls:

public getPriceList(): Observable<CuttingGapPartPrice[]> {
    const list = sessionStorage.getItem(this.listSessionKey);
    if (list) {
        return of(JSON.parse(list) as CuttingGapPartPrice[]);
    }

    return super.getClient()
        .get(`/api/cutting-gap-part-prices`, { headers: super.getHeaders() })
        .pipe(map(response => {
            sessionStorage.setItem(this.listSessionKey, JSON.stringify(response));
            return response ? response as CuttingGapPartPrice[] : new Array<CuttingGapPartPrice>();
        }));
}

public getPowerList(): Observable<MotorPower[]> {
    const list = sessionStorage.getItem(this.listSessionKey);
    if (list) {
        return of(JSON.parse(list) as MotorPower[]);
    }

    return super.getClient()
        .get(`/api/motor-power`, { headers: super.getHeaders() })
        .pipe(map(response => {
            sessionStorage.setItem(this.listSessionKey, JSON.stringify(response));
            return response ? response as MotorPower[] : new Array<MotorPower>();
        }));
}

While each individual method performs flawlessly, their combination or nesting does not produce the expected outcome.

Nested Call utilizing MergeMap:

public getQuotationPrices(quotation: Quotation): Observable<QuotationPrices> {
    return this.cuttingGapPartPriceService.getPriceList().pipe(mergeMap(prices => {
        return this.motorPowerService.getPowerList().pipe(map(powers => {
            var result = new QuotationPrices();
            //Custom logic goes here

            return result;
        }));
    }));
}

The issue I am facing bears similarity to that discussed in this thread, yet I am unable to comprehend how to resolve it.

Edit - Nested Call using ForkJoin:

public getQuotationPrices(quotation: Quotation): Observable<QuotationPrices> {
    return forkJoin([this.cuttingGapPartPriceService.getPriceList(), this.motorPowerService.getPowerList()]).pipe(map(data => {
        const prices = data[0];
        const powers = data[1];
        var result = new QuotationPrices();

        //Further processing here

        return result;
    }));
}

View of network activity in Chrome's developer tools: https://i.sstatic.net/p2Yld.png

Answer №1

Consider flattening the nested observables for better performance. It's possible that your inner observables are not being subscribed to (Observables only run when they are subscribed). Take a look at this stackblitz example to understand how nested observables need to be subscribed to or flattened in order to work properly. Additionally, following @JB Nizet's advice, creating a repository on stackblitz would be highly beneficial.

Answer №2

After some investigation, I was able to identify the root cause of the issue. Surprisingly, it wasn't related to the observables at all. I had initially set up interceptors in the AppModule, only to realize that they were being overridden by my SharedModule due to me importing the HTTPClientModule of Angular once again. By removing the duplicate import, I was able to successfully resolve the problem.

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

Angular2: Retrieving the XLS file received from the backend

I am utilizing Laravel 5.1 REST API along with the maatwebsite solution to create an Excel file from the back-end. My main goal is to initiate the download of the file upon button click. Currently, I am making an AJAX request through Angular2's Http s ...

Managing the sequence of observable requests

One of the services I provide involves conducting validation checks before sending a request to my backend server. fetchData(systems?: string[], options?: {}): Observable<System[]> { if ( // check cache ) { // validate option ...

Searching for TypeScript type definitions for the @Angular libraries within Angular 2

After updating my application to Angular2 v2.0.0-rc.1, I am encountering TypeScript compile errors and warnings when webpack bundles my application. These messages appear for any @angular packages referenced in my TypeScript source files: ERROR in ./src/a ...

Exploring Substrings in TypeScript strings

Can you pass a partial string (substring) as a value to a function in TypeScript? Is something like this allowed? function transform( str: Substring<'Hello world'> ) { // ... } If I call the function, can I pass a substring of that st ...

How to effectively implement form-control with mat-radio-group?

UPDATE: Check out my code on stackblitz I'm facing an issue with my form layout. The form control rows are overlapping with the radio button rows. I need help to resolve this problem. Here is a snippet of my code: <form [formGroup]="formGroup" (n ...

The Angular Material Table is not showing any data on the screen

My challenge is to consolidate data from 4 different endpoints in order to generate a ListElement that will populate an angular material table. Despite receiving the correct data in my logs, the table remains empty. Interestingly, when I include a conditio ...

Angular: Eliminating code duplication through service transfer

One code snippet that I frequently use when booting the app is (ngOnInit): this.route.queryParamMap.subscribe( params => { const id = params.get('id'); if (id) { this.contactsService.GetContactByUserId(id) .subscribe( ...

Mastering Angular Apollo Error Resolution Methods

Hey everyone, I'm facing a problem with apollo-angular and apollo-link-error that I just can't seem to figure out. I've experimented with different approaches but have had no luck catching errors on the client-side of my angular web app. Bel ...

When using an Angular2 application that relies on an external reference to Auth0Lock, the application encounters a NotFound error when executed

For my latest project, I decided to create an app using angular2-seed as a base. Everything was going smoothly until I tried deploying the production build on an Azure website. To my surprise, I encountered an issue when trying to load the page: > Refe ...

Generating observables from form submission event

Note: I am completely new to Angular and RXJS. Currently, I am working on a simple form where I want to create an observable. The goal is to listen for submit events and update a value within the component. However, I keep encountering an error message sa ...

Dynamic getter/setter in Typescript allows for the creation of functions

I'm facing a challenge in making Typescript automatically infer types for dynamically created getter and setter functions. In my code, I have a class called MyClass which contains a map of containers: type Container = { get: () => Content s ...

Troubleshooting error in Angular 5 with QuillJS: "Parchment issue - Quill unable to

I've been working with the primeng editor and everything seems fine with the editor itself. However, I've spent the last two days struggling to extend a standard block for a custom tag. The official documentation suggests using the quilljs API fo ...

There are no properties shared between type 'dateStyle: string' and type 'DateTimeFormatOptions'

"typescript": "^4.0.3" Can anyone help me resolve the TypeScript error I am encountering in the code below?: components/OrderListItem.tsx const newedate = (_date) => { const options = {dateStyle: 'medium'}; //{ weekday: ...

Searching within an Angular component's DOM using JQuery is restricted

Want to incorporate JQuery for DOM manipulation within Angular components, but only want it to target the specific markup within each component. Trying to implement Shadow DOM with this component: import { Component, OnInit, ViewEncapsulation } from &apo ...

The node controller function is receiving an undefined object value

Recently, I built a contact form using Angular 7 and connected it with Nodemailer to send the form details to a specified email upon submission. While the frontend view functions properly and sends values correctly, I encountered an issue on the backend wh ...

TypeScript encounters difficulty locating the div element

Recently attempted an Angular demo and encountered an error related to [ts] not being able to locate a div element. import { Component } from "@angular/core"; import { FormControl } from "@angular/forms"; @Component({ selector: "main", template: ' ...

Ways to center a spinner on the screen using CSS during loading

Upon loading the page, my spinner appears in the center of the screen after a second. However, in the initial frame of the page, it is not centered but positioned on the top-left corner instead. How can I ensure that my spinner starts off centered from the ...

Styling multiple checkbox items in an Angular Material Autocomplete

Is there a way to adjust the height of autocomplete multiple checkbox items in Angular Material? I'd like it to look like this With a line item height of 18px But instead, it looks like this when using multiple checkboxes With a different checkbox ...

Angular 8: When deployed on Heroku, subscribing to an observable yields HTML instead of JSON, however, this issue does not occur when

Issue Synopsis Encountering an error message stating Unexpected token < in JSON at position 0 at JSON.parse while attempting to fetch data from MongoDB. The code functions correctly in Angular 7, and when running locally in Angular 8, but fails when de ...

Leverage Prisma's auto-generated types as the input type for functions

Exploring the capabilities of Prisma ORM has led me to experiment with creating models and generating the PrismaClient. Initially, I thought it would be possible to utilize the generated types for variables and response types, but that doesn't seem to ...