angularrefresh-tokenangular-http-interceptorsangular-standalone-componentsangular18

Angular 18.0.5 not seeing the interceptor and not working


I believe with standalone component and HttpInterceptor has a bug!

export const appConfig: ApplicationConfig = {
  providers: [
    // provideHttpClient(withInterceptorsFromDi()),
    // {  provide:  HTTP_INTERCEPTORS, useClass: 
   // HttpAuthenticationInterceptorService, multi: true  },
    
    provideHttpClient(withInterceptors([interceptorFN])),

    provideRouter(routes),
    provideAnimationsAsync(),
    provideFirebaseApp(() => initializeApp(environment.firebase)),
    provideAuth(() => getAuth()),
    provideFirestore(() => getFirestore())
  ]
};
 

Then added the interceptor in the provider .

//Main.ts
bootstrapApplication(AppComponent, appConfig)
  .catch((err) => console.error(err));


// bootstrapApplication(AppComponent, {
//   providers: [
//     provideHttpClient(withInterceptorsFromDi()),
//     {  provide:  HTTP_INTERCEPTORS, useClass: HttpAuthenticationInterceptorService, multi: // true  },

//     provideHttpClient(withInterceptors([interceptorFN])),
//     provideRouter(routes),
//     provideAnimationsAsync(),
//     provideFirebaseApp(() => initializeApp(environment.firebase)),
//     provideAuth(() => getAuth()),
//     provideFirestore(() => getFirestore())


//   ]
// }).catch((err) => console.error(err));

I created a Service to use also tried the Di pattern in app.config.ts, not working too.

//interception Service
@Injectable({
  providedIn: 'root'
})
export class HttpAuthenticationInterceptorService implements HttpInterceptor {

  constructor(private auth: AuthenticationService) {
  }
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return this.auth.tokenResponse$.pipe(take(1), exhaustMap(response => {
      console.log("tokenResponse$; ", response);
      if (!response) {
        console.log("No Response; ", response);
        return next.handle(req);
      }
      /**Clonando o request , pois original não pode ser SETADO, é IMUTÁVEL */
      const modifiedHeader = req.clone({
        params: new HttpParams().set('auth', response.idToken)

        // setHeaders: {
        //   Authorization: response.idToken
        // }
        /**Ou */
      });
      return next.handle(modifiedHeader);
    }));
  }

  
}

I created a Function to use Interception withInterceptors(...) not working too


  
     
export const interceptorFN: HttpInterceptorFn = (req, next) => {
  const authService = inject(AuthenticationService);

  return authService.tokenResponse$.pipe(take(1), exhaustMap(token => {
    console.log("dentro do interceptor");
    if (!token) {
      return next(req);
     }
     const modifiedHeader = req.clone({
      params: new HttpParams().set('auth', token.idToken)
     })
     return next(modifiedHeader);
  }));

}

I tried to put the provides: [...] in the app.components


Solution

  • Only requests made through HttpClient are intercepted by Angular interceptors; I am thinking you are not using any API calls made through HttpClient.

    Note: Firebase methods like signInWithEmailAndPassword and other Firebase auth methods are not intercepted by Angular interceptors, since they are not made through HttpClient.

    When working with Firebase APIs, there is no need to attach any tokens; it's taken care of internally in Angular Fire.