2017-08-11 9 views
17

複数の独立したHTTPインターセプタをAngular 4アプリケーションに追加するにはどうすればよいですか?Angularアプリケーションに複数のHTTPインターセプタを追加する

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

あなたは 'Http'をオーバーライドしています。最後のオーバーライドのみが使用されます。インターセプタ1は無視されず、存在しません。インターセプタが含まれているHttpClientを使用できます。 – estus

+0

@estus「インターセプタが含まれているHttpClientを使用できますか?」とはどういう意味ですか? – str

+0

https://angular.io/guide/http – estus

答えて

36

Httpでは、カスタム実装を複数持つことはできません。しかし、@estusがAngularチームが複数のインターセプタコンセプトをサポートする最近のHttpClientサービス(リリース4.3)を追加したと述べました。あなたは古いHttpと同じようにHttpClientを拡張する必要はありません。

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(); 
    } 
} 
あなたは 'multi: true'オプションを使用して配列にすることができます代わりに HTTP_INTERCEPTORSの実装を提供することができます
+0

'api'呼び出しには1つの' interceptor'だけで傍受できることを伝える方法はありますか?または任意の条件によって? – k11k2

関連する問題