2017-10-07 56 views

回答

0

LINK應該幫助如何編寫攔截器。

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

@Injectable() 
export class AngularInterceptor implements HttpInterceptor { 
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { 
    return next.handle(req).do(event => {}, err => { 
     if(err instanceof HttpErrorResponse){ 
      console.log("Error Caught By Interceptor"); 
      //Observable.throw(err); 
     } 
    }); 
    } 
} 

撐着在

@NgModule({ 
    declarations: [ 
     AppComponent 
    ], 
    imports: [ 
     BrowserModule, 
     HttpClientModule 
    ], 
    providers: [ 
     [ { provide: HTTP_INTERCEPTORS, useClass: 
       AngularInterceptor, multi: true } ] 
    ], 
    bootstrap: [AppComponent] 
}) 
export class AppModule { 
} 
+0

當我添加提供「HTTP_INTERCEPTORS」時,我會收到一個錯誤「NoopInterceptorService沒有提供者!」 {提供:HTTP_INTERCEPTORS,useClass:AngularInterceptor,multi:true} – toney

0

首先,爲了實現攔截器,你已經使用HttpClientModule而不是HttpModule任何HTTP調用。

現在,執行:

在你App.module.ts文件,導入:

import {HttpClientModule, HTTP_INTERCEPTORS} from '@angular/common/http'; 

和你的進口數組中AppModule添加以下內容:

imports: [ 
     . 
     HttpClientModule, 
     . 
    ] 

您的提供商陣列和NoopInterceptorService實施似乎是正確的。但是,重要的是,無論何時您將在任何組件代碼中使用http方法,請不要忘記使用http方法HttpClientModule而不是舊的HttpModule

我想如果你遵循這個,你的INTERCEPTORS將會工作。

+0

這就是我寫的,但是我得到一個錯誤「NoopInterceptorService沒有提供者!」 – toney

相關問題