How to create an Http instance without using constructor DI?

半城伤御伤魂 提交于 2019-12-13 16:39:18

问题


For some reason, I don't want to use constructor(private http: Http) DI.

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

and tried

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

this.http = injector.get(Http);

Error says

ORIGINAL EXCEPTION: Cannot resolve all parameters for 'XHRConnection'(?, ?, ?). Make sure that all the parameters are decorated with Inject or have valid type annotations and that 'XHRConnection' is decorated with Injectable.


回答1:


You need to provide HTTP_PROVIDERS:

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



回答2:


Actually, it can be as simple as

const injector = ReflectiveInjector.resolveAndCreate([
  HTTP_PROVIDERS
]);

this.http = injector.get(Http);

Based on Günter Zöchbauer's answer.



来源:https://stackoverflow.com/questions/39209217/how-to-create-an-http-instance-without-using-constructor-di

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