Error:No provider for NoopInterceptorService! in angular 4.3.6?

Error:No provider for NoopInterceptorService! in angular 4.3.6?

我写了一个简单的拦截器"NoopInterceptorService"

但我得到一个错误 "No provider for NoopInterceptorService!" ,

可能是什么原因?

如何解决?

首先,为了实施 INTERCEPTOR,您必须对任何 http 调用使用 HttpClientModule 而不是 HttpModule

现在,实施:

在您的 App.module.ts 文件中,导入:

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

然后在你的导入数组中AppModule添加以下内容:

  imports: [
      .
      HttpClientModule,
       .
  ]

您的供应商数组和 NoopInterceptorService 实施似乎是正确的。但是,重要的是,无论何时在任何组件代码中使用 http 方法,都不要忘记使用 HttpClientModule 的 http 方法而不是旧的 HttpModule

我想如果你遵循这个,你的拦截器就会起作用。

这篇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);
        }
    });
  }
}

P插件

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