[Solved] HTTP Interceptor is not working in Angular 17 project – Angular

by
Alexei Petrov
angular angular-httpclient angular-httpclient-interceptors

Quick Fix: In Angular standalone workspaces, use functional interceptors with the ‘withInterceptors()’ function. Configure providers in ‘appConfig’ and define the interceptor logic separately.

The Problem:

In an Angular project, the AuthInterceptor isn’t functioning as intended. Even though the interceptor is incorporated into the application, its intercept method isn’t activated before HTTP requests. As a result, the token isn’t added to the HTTP requests, leading to authentication issues.

The Solutions:

\n

Solution 1: Use functional interceptors in standalone workspaces

\n

In standalone workspaces, functional interceptors are recommended. You can provide these interceptors using the `withInterceptors()` function. This function takes an array of interceptor functions as its argument, and it returns a provider that can be added to the `ApplicationConfig`. The interceptor function itself is a function that accepts an `HttpRequest` and an `HttpHandler`, and it returns an `Observable` of `HttpEvent`.

To use functional interceptors in your Angular 17 project, you can make the following changes:

  1. In your `main.ts` file, modify the `appConfig` object to use the `withInterceptors()` function to provide the `authInterceptor`:
export const appConfig: ApplicationConfig = {
  providers: [
    provideHttpClient(withInterceptors([authInterceptor]))
  ],
};
  1. Update your `authInterceptor` to be a function that accepts an `HttpRequest` and an `HttpHandlerFn` and returns an `Observable` of `HttpEvent`:
export function authInterceptor(
  req: HttpRequest<unknown>,
  next: HttpHandlerFn): Observable<HttpEvent<unknown>> {

  // ...interceptor login
  return next(req);
}

Refer to the [official interceptors guide](https://angular.dev/guide/http/interceptors) for more information.

Q&A

Does my Angular application need to use the @NgModule() annotation for interceptors?

No, you can use functional interceptors, which don’t require @NgModule().

Video Explanation:

The following video, titled "Solved: Angular Material Spinner is not Showing, not Working ...", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

https://codedocu.com/Net-Framework/ASP_dot_Net-Core/Angular/Errors/Angular-Mat--Spinner-is-not-Showing,-not-Working-not-Visible?2674 ng add ...