Inject Http manually in Angular 4

前端 未结 4 1181
一整个雨季
一整个雨季 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:03

    You can use HttpClient service before the Angular starts using ReflectiveInjector like this:

    import { ReflectiveInjector } from '@angular/core';
    import { HttpClient, HttpClientModule } from '@angular/common/http';
    const injector = ReflectiveInjector.resolveAndCreate(getAnnotations(HttpClientModule)[0].providers);
    
    const http = injector.get(HttpClient);
    http.get('/posts/1').subscribe((r) => {
      ConfigurationService.configuration = JSON.parse(config);
      platformBrowserDynamic().bootstrapModule(AppModule);
    });
    

    This line:

    getAnnotations(HttpClientModule).providers
    

    references all providers that are registered on the HttpClientModule so you don't have to specify them manually. This answer explains the getAnnotations function in great details.

    The approach I've shown is "sort of" the similar to what you're doing when importing HttpClientModule into the AppModule:

    @NgModule({
        imports: [HttpClientModule, ...],
    })
    export class AppModule {}
    

    See this plunker for details.

提交回复
热议问题