Bootstrap Angular 2 app with a provider that requires asynchronous initialization [duplicate]

烂漫一生 提交于 2019-12-12 03:58:58

问题


I'd like to keep my Angular 2 app config in a separate config.json file that is loaded when the app is bootstrapped.

I plan to serve the config data via ConfigService. But it needs to fetch the data from the file before any other component can ask for it.

My app is currently bootstrapped like this:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppComponent, routes } from './app';
...

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    routes
  ],
  declarations: [
    AppComponent
  ],
  [
    ConfigService,
    ...
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

platformBrowserDynamic().bootstrapModule(AppModule)

So I am looking for a way how to init the ConfigService before the app is bootstrapped. Or maybe init it when the app is bootstrapped but make any consumer wait until it is done loading.


回答1:


Following high level may works:

  1. Wrap your current app inside a ShellComponent which has following template

    <div *ngIf="ready">
        <app-component></app-component>
    </div>
    
  2. ShellComponent will call ConfigService in ngOnInit(). In callback set ready to true when ConfigService return the config.

Instead of bootstrapping AppComponent, you bootstrap ShellComponent.



来源:https://stackoverflow.com/questions/42987281/bootstrap-angular-2-app-with-a-provider-that-requires-asynchronous-initializatio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!