Inject Http manually in Angular 4

前端 未结 4 1180
一整个雨季
一整个雨季 2020-12-03 16:36

I want to manually bootstrap an Angular 4 app (created with CLI). In main.ts I am doing this:

const injector = ReflectiveInjector.resolveAndCrea         


        
4条回答
  •  难免孤独
    2020-12-03 17:20

    Possibly the original answer worked before, but in Angular 5 I was not able to use it, there was no definition for the function getAnnotations. This is what did work for me however:

    import { ReflectiveInjector } from '@angular/core';
    import {
      HttpClient,
      XhrFactory,
      HttpHandler,
      HttpXhrBackend,
      HttpBackend
    } from '@angular/common/http';
    
    // https://github.com/angular/angular/blob/master/packages/common/http/src/xhr.ts#L45
    export class BrowserXhr implements XhrFactory {
      build(): any { return (new XMLHttpRequest()); }
    }
    
    const injector = ReflectiveInjector.resolveAndCreate([
      HttpClient,
      HttpXhrBackend,
      { provide: HttpBackend, useExisting: HttpXhrBackend },
      { provide: HttpHandler, useExisting: HttpBackend },
      { provide: XhrFactory, useClass: BrowserXhr},
    ]);
    
    const http: HttpClient = injector.get(HttpClient);
    
    http.get('/url').subscribe((response) => {
      console.log(response);
    });
    

提交回复
热议问题