如何在不使用构造函数DI的情况下创建Http实例?

时间:2016-08-29 14:53:18

标签: http angular dependency-injection

出于某种原因,我不想使用构造函数(私有http:Http)DI。

看着https://angular.io/docs/ts/latest/api/http/index/Http-class.html

并尝试了

const injector = ReflectiveInjector.resolveAndCreate([
  BaseRequestOptions,
  XHRConnection,
  {
    provide: Http,
    useFactory: (backend, defaultOptions) => new Http(backend, defaultOptions),
    deps: [XHRConnection, BaseRequestOptions]
  }
]);

this.http = injector.get(Http);

错误说

  

原始例外:无法解析' XHRConnection'(?,?,?)的所有参数。确保所有参数都使用Inject进行修饰或具有有效的类型注释以及“XHRConnection”。用Injectable装饰。

2 个答案:

答案 0 :(得分:1)

您需要提供HTTP_PROVIDERS

const injector = ReflectiveInjector.resolveAndCreate([
  HTTP_PROVIDERS,
  XHRConnection,
  {
    provide: Http,
    useFactory: (backend, defaultOptions) => new Http(backend, defaultOptions),
    deps: [XHRConnection, BaseRequestOptions]
  }
]);

答案 1 :(得分:0)

实际上,它可以像

一样简单
const injector = ReflectiveInjector.resolveAndCreate([
  HTTP_PROVIDERS
]);

this.http = injector.get(Http);

基于GünterZöchbauer的回答。