How to create an Http instance without using const

2019-07-15 04:03发布

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.

2条回答
贪生不怕死
2楼-- · 2019-07-15 04:17

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]
  }
]);
查看更多
来,给爷笑一个
3楼-- · 2019-07-15 04:41

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.

查看更多
登录 后发表回答