Angular 库中提供的 HttpInterceptor 无法在 Angular 应用程序中运行

cha*_*nie 5 javascript typescript angular-http-interceptors angular

我正在开发一个 Angular 库,其中有一个提供HttpInterceptor. 主要思想是让这个拦截器在导入此身份验证模块的任何应用程序中自动工作,而无需对其进行任何额外的设置。

到目前为止我所拥有的是以下内容:

认证模块

@NgModule({
  imports: [ConcreteAuthModule],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: BearerInterceptor,
      multi: true
    }
  ]
})
export class AuthenticationModule {
  static forRoot(config: AuthConfig): ModuleWithProviders {
    return {
      ngModule: AuthenticationModule,
      providers: [
        {
          provide: AUTH_CONFIG,
          useValue: config
        }
      ]
    };
  }
}
Run Code Online (Sandbox Code Playgroud)

具体验证模块

@NgModule({
  imports: [ThirdPartyLibModule],
  providers: [
    {
      provide: AuthenticationService,
      useClass: ConcreteAuthService
    }
  ]
})
export class ConcreteAuthModule { }
Run Code Online (Sandbox Code Playgroud)

承载拦截器

@Injectable()
export class BearerInterceptor implements HttpInterceptor {
  constructor(private authService: AuthenticationService) { }

  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    const headers: any = {};

    if (this.authService.isUserAuthenticated()) {
      headers.Authorization = `Bearer ${this.singleSignOnService.getUserToken()}`;
    }

    const authReq = req.clone({ setHeaders: headers });

    return next.handle(authReq);
  }
}
Run Code Online (Sandbox Code Playgroud)

从测试 Angular 应用程序中,我在 AppModule 中按以下方式导入此模块

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    HttpClientModule,
    AuthenticationModule.forRoot({ /* config stuff */ })
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}
Run Code Online (Sandbox Code Playgroud)

我检查了一些第三方库是如何做到这一点的,还遇到了几个讨论此问题的 Stack Overflow 问题,他们都建议创建一个 Angular 模块(我已经有了它:)AuthenticationModule,然后在其上提供 http 拦截器(已经也有它),最后从 Angular 应用程序导入这个模块(也这样做了)。

但是,我的应用程序中的任何 http 请求都没有被拦截。

尝试直接从我的测试应用程序导入并在AppModuleBearerInterceptor上提供它,如下所示:

import { BearerInterceptor } from 'my-lib':

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    HttpClientModule,
    AuthenticationModule.forRoot({ /* config stuff */ })
  ],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: BearerInterceptor,
      multi: true
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}
Run Code Online (Sandbox Code Playgroud)

那行得通!但这个解决方法不是我正在寻找的......