Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Http Interceptor doesn't listen to Promise events. #56443

Closed
jowc opened this issue Jun 13, 2024 · 2 comments
Closed

Http Interceptor doesn't listen to Promise events. #56443

jowc opened this issue Jun 13, 2024 · 2 comments

Comments

@jowc
Copy link

jowc commented Jun 13, 2024

Which @angular/* package(s) are the source of the bug?

common

Is this a regression?

No

Description

I'm using the latest NGRX signals and Axios for state management.

I configured an interceptor to add my access token to the header request, but it doesn't work and only works when I
use the httpClient observable approach.

The code below is my interceptor code.

export const LoggingInterceptor = (
  req: HttpRequest<unknown>,
  next: HttpHandlerFn
): Observable<HttpEvent<unknown>> => {
  const loginService = inject(LoginService);
  const tokenService = inject(TokenService);
  if (tokenService.GetAccessToken()) {
    const modifiedReq = req.clone({
      headers: new HttpHeaders().append(
        'Authorization',
        `Bearer ${tokenService.GetAccessToken()}`
      ),
    });
    return next(modifiedReq).pipe(
      catchError((err) => {
        console.error(err);
        if (err?.status === 201) {
          loginService.deleteTokenAndRedirect();
        }
        return throwError(() => of(err));
      })
    );
  }
  return next(req);
};

Below is the Axios promise function that doesn't get noticed by the interceptor.

async logOut() {
  try {
    patchState(LoginStoreState, { logoutStatus: 'loading' });
    const res = await axios.post(`${environment.baseUrl}/api/account/logout`);
    if (res.data?.status === true) {
      patchState(LoginStoreState, { logoutStatus: 'success' });
      this.tokenService.DeleteAccessToken();
      this.router.navigate(['/auth/login']);
    }
  } catch (error: any) {
    console.error(error);
    patchState(LoginStoreState, (state) => ({
      logoutStatus: 'error' as StatusState,
      data: {
        ...state.data,
        message: AxiosErrorHandler(error),
      } as LoginModels.LoginResInterface,
    }));
  }
}

Below is the httpClient function that works.

  logOut() {
    patchState(LoginStoreState, { logoutStatus: 'loading' });
    this.http
      .post<ServerResInterface>(
        `${environment.baseUrl}/api/account/logout`,
        undefined
      )
      .pipe(
        take(1),
        tap((res) => {
          if (res?.status === true) {
            patchState(LoginStoreState, { logoutStatus: 'success' });
            this.deleteTokenAndRedirect();
          }
        })
      )
      .subscribe({
        error(err) {
          console.error(err);
          patchState(LoginStoreState, (state) => ({
            logoutStatus: 'error' as StatusState,
            data: {
              ...state.data,
              message: err?.message,
            } as LoginModels.LoginResInterface,
          }));
        },
      });
  }

Please provide a link to a minimal reproduction of the bug

No response

Please provide the exception or error you saw

No response

Please provide the environment you discovered this bug in (run ng version)

Angular CLI: 17.3.6
Node: 20.11.1
Package Manager: npm 10.2.4
OS: darwin x64

Angular: 17.3.7
... animations, common, compiler, compiler-cli, core, forms
... localize, platform-browser, platform-browser-dynamic
... platform-server, router

Package                         Version
---------------------------------------------------------
@angular-devkit/architect       0.1703.6
@angular-devkit/build-angular   17.3.6
@angular-devkit/core            17.3.6
@angular-devkit/schematics      17.3.6
@angular/cdk                    17.3.10
@angular/cli                    17.3.6
@angular/material               17.3.10
@angular/ssr                    17.3.6
@schematics/angular             17.3.6
rxjs                            7.8.1
typescript                      5.4.5
zone.js                         0.14.5

Anything else?

No response

@JoostK
Copy link
Member

JoostK commented Jun 13, 2024

Angular's HTTP interceptors are specific to Angular's HttpClient, using different clients will not consult the interceptors.

@JoostK JoostK closed this as not planned Won't fix, can't repro, duplicate, stale Jun 13, 2024
@angular-automatic-lock-bot
Copy link

This issue has been automatically locked due to inactivity.
Please file a new issue if you are encountering a similar or related problem.

Read more about our automatic conversation locking policy.

This action has been performed automatically by a bot.

@angular-automatic-lock-bot angular-automatic-lock-bot bot locked and limited conversation to collaborators Jul 14, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants