错误:angular2 中没有 HttpHandler 的提供者

Posted

技术标签:

【中文标题】错误:angular2 中没有 HttpHandler 的提供者【英文标题】:Error: No provider for HttpHandler in angular2 【发布时间】:2018-02-10 13:10:23 【问题描述】:

我正在尝试通过拦截器实现 HttpCache。以下是caching-interceptor.service.ts

import  HttpRequest, HttpResponse, HttpInterceptor, HttpHandler, HttpEvent  from '@angular/common/http'
import  Injectable  from '@angular/core';
import  Observable  from 'rxjs/Observable';

import 'rxjs/add/operator/do';
import 'rxjs/add/observable/of';

export abstract class HttpCache 
  abstract get(req: HttpRequest<any>): HttpResponse<any>|null;
  abstract put(req: HttpRequest<any>, resp: HttpResponse<any>): void;




@Injectable()
export class CachingInterceptor implements HttpInterceptor 
    constructor(private cache: HttpCache) 

    intercept(req: HttpRequest<any>, next: HttpHandler) : Observable<HttpEvent<any>> 
        if(req.method !== 'GET')
            return next.handle(req);
        

        const cachedResponse = this.cache.get(req);

        if(cachedResponse)
            return Observable.of(cachedResponse);
        

        return next.handle(req).do(event => 
            if(event instanceof HttpResponse)
                this.cache.put(req, event);
            
        )
    

我从 test.service.ts 打来电话

import  Injectable  from '@angular/core';
import  Headers, Http, Response from '@angular/http';
import  HttpClient from '@angular/common/http';
import  Observable  from 'rxjs/Observable';
import  ReplaySubject  from 'rxjs/ReplaySubject';

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

import  BehaviorSubject  from 'rxjs/BehaviorSubject';

import  APIService  from './api.service';
import  CachingInterceptor  from './caching-interceptor.service';
import  ConfigurationService  from './configuration.service';
import  AuthenticationStatus, IAuthenticationStatus  from '../models';
import  User  from '../models/user.model';

@Injectable()
export class PlatformService extends APIService 



  constructor(private http: Http, public httpClient: HttpClient, private configuration: ConfigurationService,
     public cachingInterceptor: CachingInterceptor) 
    super();


  

  getUserById(id: string) 
    console.log(this.requestOptions);
    return this.httpClient.get(this._getAPIUrl('user/' + id),this.requestOptions).
      subscribe(res => res);
  
  get requestOptions(): RequestOptions 
    const tokenObj = window.localStorage.getItem('TOKEN');
    const token = JSON.parse(tokenObj);
    const headers = this.headers;
    headers.append('Authorization', 'Bearer ' + token.token);
    headers.append('Access-Control-Allow-Origin', '*');
    return new RequestOptions( headers: headers );
  



模块文件如下

import  CommonModule  from '@angular/common';
import  HTTP_INTERCEPTORS, HttpClient  from '@angular/common/http';
import  FormsModule  from '@angular/forms';

import  ModuleWithProviders, NgModule  from '@angular/core';

import  PlatformService  from '../../services/platform.service';
import  CachingInterceptor  from '../../services/caching-interceptor.service';


@NgModule(
  imports: [CommonModule, FormsModule],

  declarations: [],

  exports: [],

  entryComponents: [EntryHereComponent]
)
export class StructurModule 
  public static forRoot(): ModuleWithProviders 
    return  ngModule: StructurModule, providers: [PlatformService,
       
        provide: HTTP_INTERCEPTORS,
        useExisting: CachingInterceptor,
        multi: true
    ,HttpClient] ;
  

我不明白,缺少什么所以它给出错误

没有 HttpHandler 的提供者。

如果我在模块文件的提供程序中添加 HttpHandler,它开始给出错误提供:HTTP_INTERCEPTORS,组件。

【问题讨论】:

【参考方案1】:

HttpClient是在angular 4.3中引入的,所以如果你想使用HttpClient你需要从'@angular/common/http'导入HttpClientModule。确保在BrowserModule 之后导入HttpClientModule,如下所示。 official doc 和 so answer 将为您提供深入的信息。

import  HttpClientModule  from '@angular/common/http';

@NgModule(
 imports: [
   BrowserModule,
   HttpClientModule
 ],
 ...

【讨论】:

哇!我在路由之后包含了 HttpClientModule !但它不起作用,谢谢! 这应该是公认的答案。仍然适用于 Angular 5 也适用于 Angular 8 也适用于 Angular 12【参考方案2】:

将 HttpClientModule 添加到 app.module.ts 中的导入[]。这可能是错误之一。

【讨论】:

以上是关于错误:angular2 中没有 HttpHandler 的提供者的主要内容,如果未能解决你的问题,请参考以下文章

Angular2 错误 - 我的登录组件没有提供程序错误

在 IE10 中升级到 Angular2 RC5 后没有提供 PlatformRef 错误

错误:ENOENT:Angular2 和 Express.js 没有这样的文件或目录

Angular2延迟加载模块错误'找不到模块'

在angular2中自动调整textarea

从angular2访问web-api时没有'Access-Control-Allow-Origin'错误[重复]