Angular HttpInterceptor doesn't get the updated values of a SignalStore's Signal

Discussão em 'Angular' iniciado por Sofoklis Marmarelis, Junho 11, 2025.

  1. I have a casual HttpInterceptor:

    import {
    HttpEvent,
    HttpHandler,
    HttpInterceptor,
    HttpRequest,
    } from '@angular/common/http';
    import { catchError, finalize, Observable, throwError } from 'rxjs';
    import { Injectable, Injector } from '@angular/core';
    import { AppStore } from '../store/app.store';

    @Injectable()
    export class MyInterceptor implements HttpInterceptor {
    constructor(private injector: Injector) {}

    intercept(
    req: HttpRequest<any>,
    next: HttpHandler
    ): Observable<HttpEvent<any>> {
    // Has to be injected this way, otherwise it is undefined or leads to circular dependency issues
    const appStore = this.injector.get(AppStore);
    if (appStore.userId() != null) {
    req = req.clone({
    setHeaders: {
    'x-session-userId': appStore.userId()!.toString(),
    },
    });
    }
    return next.handle(req).pipe(
    catchError((err: any, caught: Observable<any>) => {
    // ...do stuff
    return throwError(() => err);
    }),
    finalize(() => {})
    );
    }
    }


    I also have a SignalStore which, for simplicity, we will assume is this:

    import {
    patchState,
    signalStore,
    withMethods,
    withState,
    } from '@ngrx/signals';

    type AppState = {
    userId: number | null;
    };

    const initialState: AppState = {
    userId: null,
    };

    export const AppStore = signalStore(
    withState(initialState),
    withMethods((store) => ({
    selectUserId(selection: number) {
    patchState(store, {
    userId: selection,
    });
    },
    })),
    );


    Now, at first, before selectUserId() is ever run, the intercept() method evaluates appStore.userId() as null and essentialy does nothing. After the first time selectUserId() is run, the intercept() method evaluates appStore.userId() as != null and perfectly does what it's supposed to do, sets 'x-session-userId' to the correct value (let's say 'x-session-userId': '10'). BUT, after the second time selectUserId() is run, the intercept() method evaluates appStore.userId() as != null BUT it still has the previous value, leading to 'x-session-userId': '10', even though I have clearly set appStore.userId() to a different value than 10.

    How is that possible? How can I fix this?

    I also tried to use an effect() inside my Interceptor that didn't ever run more than one time.

    Continue reading...

Compartilhe esta Página