Inject Http manually in Angular 2

前端 未结 2 1691
-上瘾入骨i
-上瘾入骨i 2020-12-03 18:18

I have created a Base Model in which I have all the common functions to fetch data and post or put the data. Actually what a service does in Angular but I don\'t want a serv

相关标签:
2条回答
  • 2020-12-03 18:52

    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

    0 讨论(0)
  • 2020-12-03 19:09

    Ugly solution which works in Angular 2.1

    import {ReflectiveInjector} from '@angular/core';
    import {Http, HttpModule} from "@angular/http";
    
    const providers = (<any>HttpModule).decorators[0].args[0].providers;
    const injector = ReflectiveInjector.resolveAndCreate(providers);
    const http = injector.get(Http);
    
    0 讨论(0)
提交回复
热议问题