填写这份《一分钟调查》,帮我们(开发组)做得更好!去填写Home

APP_INITIALIZER

可用于提供一个或多个初始化功能的 DI 令牌。

A DI token that you can use to provide one or more initialization functions.

查看"说明"...

      
      const APP_INITIALIZER: InjectionToken<ReadonlyArray<() => void | Observable<unknown> | Promise<unknown>>>;
    

参见

说明

所提供的函数是在应用程序启动时注入的,并在应用程序初始化期间执行。如果这些函数中的任何一个返回 Promise,则直到 Promise 被解析之前,初始化都不会完成。

The provided functions are injected at application startup and executed during app initialization. If any of these functions returns a Promise or an Observable, initialization does not complete until the Promise is resolved or the Observable is completed.

例如,你可以创建一个工厂函数来加载语言数据或外部配置,并将该函数提供给 APP_INITIALIZER 令牌。该功能在应用程序引导过程中执行,并且所需的数据在启动时可用。

You can, for example, create a factory function that loads language data or an external configuration, and provide that function to the APP_INITIALIZER token. The function is executed during the application bootstrap process, and the needed data is available on startup.

Further information available in the Usage Notes...

使用说明

The following example illustrates how to configure a multi-provider using APP_INITIALIZER token and a function returning a promise.

      
      function initializeApp(): Promise<any> {
  return new Promise((resolve, reject) => {
    // Do some asynchronous stuff
    resolve();
  });
}

@NgModule({
 imports: [BrowserModule],
 declarations: [AppComponent],
 bootstrap: [AppComponent],
 providers: [{
   provide: APP_INITIALIZER,
   useFactory: () => initializeApp,
   multi: true
  }]
 })
export class AppModule {}
    

It's also possible to configure a multi-provider using APP_INITIALIZER token and a function returning an observable, see an example below. Note: the HttpClient in this example is used for demo purposes to illustrate how the factory function can work with other providers available through DI.

      
      function initializeApp(httpClient: HttpClient): Observable<any> {
 return httpClient.get("https://someUrl.com/api/user")
   .pipe(
      tap(user => { ... })
   )
}

@NgModule({
  imports: [BrowserModule, HttpClientModule],
  declarations: [AppComponent],
  bootstrap: [AppComponent],
  providers: [{
    provide: APP_INITIALIZER,
    useFactory: initializeApp,
    deps: [HttpClient],
    multi: true
  }]
})
export class AppModule {}