在Angular 12中使用'APP_INITIALIZER”,需要在配置文件中的'app.module.ts”和'main.ts”文件中做出一些更改。具体如下:
// 使用APP_INITIALIZER: export function initializeApp(appConfig: AppConfig) { return () => appConfig.LoadConfigData(); }
@NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule, ], providers: [ AppConfig, { provide: APP_INITIALIZER, useFactory: initializeApp, multi: true, deps: [AppConfig] } ], bootstrap: [AppComponent] }) export class AppModule { }
// 改为使用FactoryProvider: export function initializeApp(appConfig: AppConfig) { return () => appConfig.LoadConfigData(); }
export const AppConfigProvider = { provide: APP_INITIALIZER, useFactory: initializeApp, deps: [AppConfig], multi: true };
@NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule, ], providers: [ AppConfig, AppConfigProvider ], bootstrap: [AppComponent] }) export class AppModule { }
import { platformBrowser } from '@angular/platform-browser'; import { enableProdMode } from '@angular/core'; import { AppModule } from './app/app.module'; // 手动引入AppModule import { environment } from './environments/environment';
if (environment.production) { enableProdMode(); }
platformBrowser().bootstrapModule(AppModule) .catch(err => console.error(err));
通过以上两个步骤,您的'APP_INITIALIZER”就可以在Angular 12中正常工作了。