【问题标题】:Error:No provider for NoopInterceptorService! in angular 4.3.6?错误:没有 NoopInterceptorService 的提供者!在角度 4.3.6 中?
【发布时间】:2017-10-08 10:24:18
【问题描述】:

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

但我收到一个错误“没有 NoopInterceptorService 的提供者!” ,

可能是什么原因?

如何解决?

【问题讨论】:

  • 您是否在根模块中导入了 HttpClientModule?

标签: angular angular-http-interceptors


【解决方案1】:

这个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 {
}

【讨论】:

  • 当我添加提供“HTTP_INTERCEPTORS”时,我会得到一个错误“NoopInterceptorService 没有提供者!” { 提供:HTTP_INTERCEPTORS,useClass:AngularInterceptor,multi:true }
【解决方案2】:

首先,为了实现 INTERCEPTOR,您必须使用 HttpClientModule 而不是 HttpModule 进行任何 http 调用。

现在,实现:

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

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

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

  imports: [
      .
      HttpClientModule,
       .
  ]

您的 providers 数组和 NoopInterceptorService 实现似乎是正确的。但是,重要的是,每当您在任何组件代码中使用 http 方法时,请不要忘记使用 HttpClientModule 的 http 方法而不是旧的 HttpModule

我认为,如果您遵循这一点,您的拦截器就会起作用。

【讨论】:

  • 这就是我写的,但是我得到一个错误“No provider for NoopInterceptorService!”
猜你喜欢
  • 2018-08-08
  • 2018-03-04
  • 2019-08-12
  • 1970-01-01
  • 1970-01-01
  • 2021-05-19
  • 2022-11-24
  • 2018-06-21
  • 2018-02-28
相关资源
最近更新 更多