填寫這份《一分鐘調查》,幫我們(開發組)做得更好!去填寫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 {}