错误:在angular2中没有HttpHandler的提供程序 [英] Error: No provider for HttpHandler in angular2

查看:105
本文介绍了错误:在angular2中没有HttpHandler的提供程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to implement HttpCache through interceptor. Following is the 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打电话

and I am calling from 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] };
  }
}

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

I don't understand, what are missing so it giving error

没有HttpHandler的提供程序.

No provider for HttpHandler.

如果我在模块文件的提供程序中添加HttpHandler,它将开始提供以下错误:提供HTTP_INTERCEPTORS,组件.

If I add HttpHandler in provider in module file, It start giving error for provide: HTTP_INTERCEPTORS, component.

推荐答案

HttpClient是在angular 4.3中引入的,因此,如果要使用HttpClient,则需要从'@angular/common/http'导入HttpClientModule.如下所示,确保在BrowserModule之后导入HttpClientModule.此官方文档

HttpClient is introduced in angular 4.3,so if you want to use HttpClient you need to import HttpClientModule from '@angular/common/http'. Make sure to import HttpClientModule after BrowserModule as shown below. This official doc and so answer will give you indepth information.

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

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

这篇关于错误:在angular2中没有HttpHandler的提供程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆