Inject Http manually in Angular 2

UPDATE (final)

constructor() {
  let injector = ReflectiveInjector.resolveAndCreate([
    Http,
    BrowserXhr,
    {provide: RequestOptions, useClass: BaseRequestOptions},
    {provide: ResponseOptions, useClass: BaseResponseOptions},
    {provide: ConnectionBackend, useClass: XHRBackend},
    {provide: XSRFStrategy, useFactory: () => new CookieXSRFStrategy()},
  ]);
  this.http = injector.get(Http);
}

ORIGINAL (RC.x)

constructor() {
  let injector = ReflectiveInjector.resolveAndCreate([HTTP_PROVIDERS]);
  this.http = injector.get(Http);
}

This creates a new injector (independent of the one used by the rest of your Angular2 app. This isn’t necessarily a problem, you just should be aware of it.

See also angular2 resolveAndCreate HTTP – missing HTTP_PROVIDERS in RC7

Leave a Comment