代码之家  ›  专栏  ›  技术社区  ›  str

向Angular应用程序添加多个HTTP侦听器

  •  97
  • str  · 技术社区  · 7 年前

    我试图通过扩展 providers Interceptor1 被忽略。

    @NgModule({
      declarations: [ /* ... */ ],
      imports: [ /* ... */ HttpModule ],
      providers: [
        {
          provide: Http,
          useFactory: (xhrBackend: XHRBackend, requestOptions: RequestOptions) =>
            new Interceptor1(xhrBackend, requestOptions),
          deps: [XHRBackend, RequestOptions],
        },
        {
          provide: Http,
          useFactory: (xhrBackend: XHRBackend, requestOptions: RequestOptions) =>
            new Interceptor2(xhrBackend, requestOptions),
          deps: [XHRBackend, RequestOptions]
        },
      ],
      bootstrap: [AppComponent]
    })
    export class AppModule {}
    

    很明显,我可以把它们组合成一个 Interceptor 上课,这应该管用。然而,我希望避免这种情况,因为这些拦截器有完全不同的用途(一个用于错误处理,一个用于显示加载指示器)。

    1 回复  |  直到 7 年前
        1
  •  184
  •   hiper2d    7 年前

    Http 不允许有多个自定义实现。但是正如@estus提到的,Angular团队增加了一个新的 HttpClient 最近的服务(4.3版),支持多拦截器概念。您不需要扩展 HttpClient 就像你对待老人一样 Http HTTP_INTERCEPTORS 相反,它可以是具有 'multi: true' 选项:

    import {HTTP_INTERCEPTORS, HttpClientModule} from '@angular/common/http';
    ...
    
    @NgModule({
      ...
      imports: [
        ... ,
        HttpClientModule
      ],
      providers: [
        ... ,
        {
          provide: HTTP_INTERCEPTORS,
          useClass: InterceptorOne,
          multi: true,
        },
        {
          provide: HTTP_INTERCEPTORS,
          useClass: InterceptorTwo,
          multi: true,
        }
      ],
      ...
    })
    

    拦截器:

    import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
    ...
    
    @Injectable()
    export class InterceptorOne implements HttpInterceptor {
    
      intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        console.log('InterceptorOne is working');
        return next.handle(req);
      }
    }
    
    @Injectable()
    export class InterceptorTwo implements HttpInterceptor {
    
      intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        console.log('InterceptorTwo is working');
        return next.handle(req);
      }
    }
    

    此服务器调用将打印两个拦截器的日志消息:

    import {HttpClient} from '@angular/common/http';
    ...
    
    @Component({ ... })
    export class SomeComponent implements OnInit {
    
      constructor(private http: HttpClient) {}
    
      ngOnInit(): void {
        this.http.get('http://some_url').subscribe();
      }
    }