在运行 Angular Universal 时,可以遇到来自外部文件的 APP_CONFIG 无法正确加载的问题。这可能导致在客户端和服务器端之间的配置差异,导致应用程序行为不一致。
解决此问题的一种方法是使用APP_INITIALIZER
函数来读取 app.config.json 并将其注入到应用程序中。这将确保在应用程序启动之前就已经将配置加载到内存中。
首先,需要创建一个服务来加载配置文件:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root',
})
export class AppConfigService {
private appConfig: any;
constructor(private http: HttpClient) {}
async loadAppConfig(): Promise {
try {
this.appConfig = await this.http.get('/assets/app.config.json').toPromise();
} catch (error) {
console.error('Error while loading app config');
}
}
getConfig(key: string): any {
return this.appConfig?.[key];
}
}
上述服务中的 loadAppConfig
方法读取来自 /assets/app.config.json
的配置文件。 getConfig
方法可以使用运算符(?.
)检查属性是否存在并返回配置中的属性。
接下来,在应用程序的模块中(如 AppModule)中使用 APP_INITIALIZER
来加载配置文件。
import { NgModule, APP_INITIALIZER } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { AppConfigService } from './app-config.service';
export function initializeApp(appConfigService: AppConfigService) {
return (): Promise => {
return appConfigService.loadAppConfig();
};
}
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, HttpClientModule],
providers: [
AppConfigService,
{
provide: APP_INITIALIZER,
useFactory: initializeApp,
deps: [AppConfigService],
multi: true,
},