How to create an Http instance without using the DI constructor? (RC.5 +)

I need to get an Http instance without using Angular2 DI (constructor (private http: Http))

The following code was taken from another thread_stack question , and it works in Angular2 RC.4 and earlier, but not in RC.5 + (HTTP_PROVIDERS is no longer available):

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

this.http = injector.get(Http);

There are several questions in Stackoverflow with different variations of the same code, but none of them work in RC.5 +.

Does anyone know how to accomplish the same thing in RC.5 +?

+4
source share
2 answers

HttpModule. , Http. , HTTP_PROVIDERS

export function _createDefaultCookieXSRFStrategy() {
  return new CookieXSRFStrategy();
}

export function httpFactory(xhrBackend: XHRBackend, requestOptions: RequestOptions): Http {
  return new Http(xhrBackend, requestOptions);
}

@NgModule({
  providers: [
    {provide: Http, useFactory: httpFactory, deps: [XHRBackend, RequestOptions]},
    BrowserXhr,
    {provide: RequestOptions, useClass: BaseRequestOptions},
    {provide: ResponseOptions, useClass: BaseResponseOptions},
    XHRBackend,
    {provide: XSRFStrategy, useFactory: _createDefaultCookieXSRFStrategy},
  ],
})
export class HttpModule {
}

providers , ReflectiveInjector.resolveAndCreate.

, Http , , , CookieXSRFStrategy. , . noop,

+3

.

, , .

service.ts

import { Injectable,Injector } from '@angular/core';
import {Http} from '@angular/http';

@Injectable()
export class Service{
    constructor(private injector:Injector){}

    display(){

        this.http=this.injector.get(Http);   //<<<<------here the magic happens

        console.log(this.http);
        return this.http.get('user.json').map(res => {return res.json()}).toPromise();
    } 
}


, , Angular2.0.0:
https://plnkr.co/edit/eWLB2BaL66pnJ7SC6qAL?p=preview

0

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


All Articles