angular - APP_INITIALIZE 后初始化模块
问题描述
在我的 Angular 6 应用程序中,我正在通过这样的 Http 服务加载我的外部化配置:
export function getSettings(appLoadService: ConfigLoadService) {
return () => appLoadService.getSettings();
}
@NgModule({
imports: [
CommonModule
],
declarations: [],
providers: [
ConfigLoadService,
{provide: APP_INITIALIZER, useFactory: getSettings, deps: [ConfigLoadService], multi: true}]
})
export class AppLoadModule {
}
服务:
@Injectable()
export class ConfigLoadService {
constructor(private http: HttpClient) {
}
getSettings(): Subscription {
console.log("Loading config from server...");
return this.http
.get("/config.json")
.subscribe((config: any) => {
AppSettings.API_BASE_URL = config.API_BASE_URL;
console.log("API_BASE_URL: " + AppSettings.API_BASE_URL);
});
}
}
现在我想添加一个外部依赖项,该依赖项需要使用现有配置进行初始化:
@NgModule({
imports:
DepModule.forRoot({
apiBaseUrl: AppSettings.API_BASE_URL
}),
],[...]
这里的问题是依赖项是在 之前导入和初始化的APP_INITIALIZER
,因此没有正确配置。我在这里想念什么?
解决方案
提供APP_INITIALIZER
者工厂方法必须返回一个承诺
所以你会做这样的事情:
@Injectable()
export class ConfigLoadService {
private myConfig;
constructor(private http: HttpClient) {
}
getSettings() {
return this.http.get('/config.json')
.toPromise()
.then(data => {
this.myConfig = data;
});
}
getConfig() {
return this.myConfig;
}
}
Juri 写了一篇关于它的博客,您可以阅读更多App Runtime Config
推荐阅读
- rpa - Automation Anywhere 文件触发器失败
- xamarin.forms - 导航后如何更改页面标题?
- android - 如何设置单个recyclerview item [imageview] 占据屏幕的一半?
- python - Python & Sqlalchemy - 连接模式 -> 随机断开与远程服务器的连接
- javascript - 使用 window.open 在 Chrome 中打开一个具有所有功能(菜单栏等)的新窗口(不是选项卡)
- wordpress - Fedora 上 Wordpress 中的永久链接损坏
- vuejs2 - vuejs - 异步和动态组件
- php - PHP Rabbit MQ 从单个队列中读取特定消息
- javascript - 从字符串打印 vue 组件
- ios - 对于 alertController:UISegmentedControl 中选定段的 sourceView 是什么