如何跨模块创建HttpInterceptor?

Rob*_*per 7 angular-http-interceptors angular angular-httpclient

我对HttpInterceptors 上 Angular 文档底部的使用说明很好奇,它指出:

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

我不明白该怎么做。如何获取根应用程序注入器并将我的延迟加载模块的 HttpInterceptor 添加到其中?

似乎How to import Angular HTTP拦截器仅适用于子模块也试图回答这个问题,但答案对我来说同样不清楚。

为什么这不起作用,以及如何正确添加第二个延迟加载拦截器?

应用程序模块

@NgModule({
  imports: [RouterModule.forRoot(routes)], // routes contains a lazy load module
  declarations: [AppComponent],
  bootstrap: [AppComponent],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: TokenInterceptorService,
      multi: true,
    }
  ]
})
export class AppModule { }
Run Code Online (Sandbox Code Playgroud)

延迟加载子模块

@NgModule({
  imports: [
    LazyRoutingModule
  ],
  declarations: [ChildComponent],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: CacheInterceptorService,
      multi: true,
    }
  ]
})
export class LazyModule { }
Run Code Online (Sandbox Code Playgroud)

Iva*_*lue 1

早上好,

请原谅我的英语,但我正在用谷歌翻译器翻译这个。

我正在开发一个带有几个惰性模块的应用程序,我刚刚开发了一个 HttpInterceptor 并且没有遇到任何问题,我所做的过程如下:

Http拦截器

import { Injectable } from '@angular/core';
import {
    HttpInterceptor,
    HttpRequest,
    HttpHandler,
    HttpEvent,
    HttpErrorResponse
} from '@angular/common/http';

import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';
import { NotifierService } from 'angular-notifier';

@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {

    constructor(private notifier: NotifierService) { }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(request).pipe(
            retry(1),
            catchError((error: HttpErrorResponse) => {
                this.notifier.notify('error', error && error.message ? error.message : 'Error');
                return throwError(error);
            }
            ));
    }
}
Run Code Online (Sandbox Code Playgroud)

并简单地导入到app.module 的提供者中添加:

{
       provide: HTTP_INTERCEPTORS,
       useClass: HttpErrorInterceptor,
       multi: true
}
Run Code Online (Sandbox Code Playgroud)

我认为你遇到的问题是,当你也在孩子中实例化时,你创建了一个新实例,这会带来问题。在这样做之前我读过几篇文章,这表明它不应该工作,但它确实有效,哈哈。

以防万一它来自某个新版本的 Angular,我将我正在处理的项目的数据放在下面:

角度 CLI:8.3.25 节点:13.3.0 角度:8.2.14