Angular 通用 HttpInterceptor 运行两次

mar*_*kus 3 angular-universal angular

我目前正在将我的 angular 应用程序切换到通用 ssr 应用程序。我的最后一个问题是我的自定义 HttpInterceptor 触发了两次。我正在检查我的 api 调用的 http 响应代码,如果出现错误,则会显示一个弹出窗口。自从我切换到通用后,我两次收到相同的错误弹出窗口。

@Injectable()
export class HttpSetHeaders implements HttpInterceptor {
  constructor(
    @Inject(PLATFORM_ID) private platformId,
    @Inject(LOCAL_STORAGE) private localStorage: any,
    private authService: AuthService,
    private router: Router,
    private notifierService: NotifierService
  ) { }
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    console.log(isPlatformServer(this.platformId))
    ......
}
Run Code Online (Sandbox Code Playgroud)

每次 HTTPClient 调用后,我都会看到两次控制台日志输出。

我在 app.module 中导入了 TransferHttpCacheModule,在 app.server.module 中导入了 TransferHttpCacheModule

谢谢马库斯

axe*_*ter 6

根据https://angular.io/api/common/http/HttpInterceptor

要为整个应用程序使用相同的 HttpInterceptors 实例,请仅在您的 AppModule 中导入 HttpClientModule,并将拦截器添加到根应用程序注入器。如果跨不同模块多次导入 HttpClientModule(例如,在延迟加载模块中),每次导入都会创建 HttpClientModule 的新副本,它会覆盖根模块中提供的拦截器。

如果这能解决您的问题,请告诉我。可能是您不止一次地实例化了 HttpInterceptor。