No provider for XHRBackend with Angular 2 and Http service

元气小坏坏 提交于 2019-12-04 08:54:38

You need to import the HttpModule in your module. The latter provides the HTTP providers including XHRBackend. Moreover if you want to implement interception for HTTP request, you need to use the Http type when registering your interceptor implementation (a sub class of Http).

Here is a sample:

imports: [
  (...)
  HttpModule, // <-------------
  (...)
],
providers: [
  {
    provide: Http, // <-------------
    useFactory: httpInterceptor,
    deps: [ XHRBackend, RequestOptions, Store, Injector ]
  }
]

You are not referencing the context (If I'm correct), try with an arrow function:

return () => new HttpService(backend, defaultOptions);

Anyways, why don't you add to your AppModule, in the imports, the module of Http (HttpModule)?

AppModule:

import { HttpModule } from '@angular/http';

imports: [ HttpModule ]

And in your service you just:

import { Injectable } from '@angular/core';
import { Http, Headers, Response, XHRBackend } from '@angular/http';

@Injectable()
export class MyService {

    constructor(private http: Http) {
         }

// Use Http's stuff
}

Then in your CoreModule you can just add:

providers: [ MyService ]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!