How to create an Http instance without using the DI constructor?

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

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 EXCLUSION: Unable to resolve all parameters for "XHRConnection" (?,?,?). Ensure that all parameters are decorated with Inject or have valid type annotations and that "XHRConnection" is decorated with Injectable.

+2
source share
2 answers

You need to specify HTTP_PROVIDERS:

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

Actually, it can be as simple as

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

this.http = injector.get(Http);

.

0

Source: https://habr.com/ru/post/1655377/


All Articles