web-dev-qa-db-ja.com

複数のHTTPインターセプターをAngularアプリケーションに追加します

複数の独立したHTTPインターセプターをAngular 4アプリケーションに追加する方法は?

providers配列を複数のインターセプターで拡張して、それらを追加しようとしました。ただし、実際に実行されるのは最後の1つだけで、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クラスに結合することができ、それは機能するはずです。ただし、これらのインターセプターの目的はまったく異なるため(エラー処理用、ロードインジケーターの表示用)、これらのインターセプターを避ける必要があります。

では、複数のインターセプターを追加するにはどうすればよいですか?

56
str

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();
  }
}
116
hiper2d