将 HTTP 拦截器添加到独立组件

Eli*_*ush 12 angular-http-interceptors angular

我试图通过将拦截器添加到providers组件本身的数组( { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true })来将拦截器添加到独立组件,但它不起作用......

这是代码的链接

谢谢 :)

rzy*_*man 32

从版本 15 开始,Angular 将能够在引导我们的应用程序和功能拦截器期间使用 ProvideHttpClient:

bootstrapApplication(AppComponent, {
providers: [
    provideHttpClient(
        withInterceptors([authInterceptor]),
    ),
]
Run Code Online (Sandbox Code Playgroud)

功能拦截器:

import { HttpInterceptorFn } from "@angular/common/http";

export const authInterceptor: HttpInterceptorFn = (req, next) => {

    req = req.clone({
        headers
    }

return next(req)
}
Run Code Online (Sandbox Code Playgroud)

如果我们可以使用基于类的拦截器,我们需要添加 withInterceptorsFromDi 选项来提供HttpClient:

bootstrapApplication(AppComponent, {
providers: [
    provideHttpClient(
        withInterceptorsFromDi(),
    ),
    {
        provide: HTTP_INTERCEPTORS,
        useClass: AuthInterceptor,
        multi: true,
    },
 ] });
Run Code Online (Sandbox Code Playgroud)

  • `withLegacyInterceptors()` 不再存在。对我来说 `withInterceptorsFromDi()` 有效 (2认同)
  • 谢谢。这是我的救赎。我浪费了很多时间来解决这个问题。不幸的是,Angular 网站上的文档非常稀疏。 (2认同)

小智 11

我在main.ts文件中这样使用它:

bootstrapApplication(AppComponent, {
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }
  ]
}
Run Code Online (Sandbox Code Playgroud)

如果您的应用程序是使用独立组件引导的,那么它就可以工作。如果您使用模块并尝试在此架构中实现独立组件,则需要将其添加到app.module.ts的提供者中。

@NgModule({
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }
  ]
})
Run Code Online (Sandbox Code Playgroud)

以下是可能有用的文档链接

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

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