2017-10-07 106 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

相关问题