angularangular-http-interceptors

Add HTTP Interceptor to standAlone component


I'm trying to add an interceptor to standalone component by adding the interceptor to the providers array in the component itself ( { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true } ), but it's not working...

here is a link to code

thanks :)


Solution

  • I used it like this in main.ts file:

    bootstrapApplication(AppComponent, {
      providers: [
        { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }
      ]
    }
    

    It works if your application is bootstrapped usig standalone component. If you use modules and try to implement standalone component within this architecture, you need to add same to providers of app.module.ts.

    @NgModule({
      providers: [
        { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }
      ]
    })
    

    Here are links from documentation that may be helpful

    https://angular.io/guide/standalone-components#bootstrapping-an-application-using-a-standalone-component

    https://angular.io/guide/http#provide-the-interceptor