在Angular中,可以使用AppConfig来保存应用程序的配置信息。通常情况下,AppConfig是在应用程序启动时从服务器加载的。如果在模块设置中需要使用AppConfig,可以使用Promise来确保在加载配置后再进行模块设置。
以下是一个示例代码:
// app-config.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class AppConfigService {
private appConfig: any;
constructor(private http: HttpClient) { }
loadAppConfig() {
return this.http.get('/api/config').toPromise()
.then(data => {
this.appConfig = data;
});
}
getConfig() {
return this.appConfig;
}
}
// app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
import { AppConfigService } from './app-config.service';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [
AppConfigService,
{
provide: APP_INITIALIZER,
useFactory: (config: AppConfigService) => () => config.loadAppConfig(),
deps: [AppConfigService],
multi: true
}
],
bootstrap: [AppComponent]
})
export class AppModule { }
// some.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { AppConfigService } from './app-config.service';
@NgModule({
imports: [
CommonModule
],
providers: [],
declarations: []
})
export class SomeModule {
constructor(private appConfigService: AppConfigService) {
const appConfig = this.appConfigService.getConfig();
// 使用appConfig进行模块设置
}
}
这样,就可以确保在模块设置中使用到AppConfig时,已经从服务器加载了配置。