gpt4 book ai didi

angular - APP_INITIALIZER 不阻止导入的模块

转载 作者:太空狗 更新时间:2023-10-29 19:32:25 24 4
gpt4 key购买 nike

我有一个 Angular (v6.0.0) 应用程序,我正试图通过在 APP_INITIALIZER 期间引入运行时配置来设置它。我已经阅读了几篇文章(例如 thisthisthis )以及诸如 this 之类的问题并且基本上一切正常。

我让应用程序调用配置服务函数以在应用程序引导时加载配置(在 APP_INITIALIZER 期间)。一切都很完美。问题是应用程序的其他部分正在加载/初始化/它们的构造函数在配置加载之前被调用,因此无法使用文件中的配置。以下是 app.module 文件的摘录:

function initConfig(configService: AppConfigService) {
return () => configService.loadConfig();
}

...

@NgModule({
imports: [AuthModule, SharedModule]
providers: [
{
provide: APP_INITIALIZER,
useFactory: initConfig,
deps: [AppConfigService],
multi: true
},
...
]
})

和 AppConfigService 文件:

public loadConfig() {
return this._http.get('./assets/app-config/config.json')
.toPromise()
.then((config: any) => {
this.config = config;
})
}

如您所见,loadConfig 函数返回一个 promise ,并加载配置(我已经确认)。

但是,我尝试访问 AuthModule 构造函数中的配置(因此我可以提取服务器身份验证所需的配置值)和 SharedModule 中的服务(在本例中正在寻找 Sentry DSN) ,它们都在加载配置之前运行。我敢肯定还有其他示例,但这是我目前所发现的。

我的印象是,在 APP_INITIALIZER 解析之前,应用程序中的任何内容都不会加载,但显然事实并非如此。我缺少什么来完成这个吗?我可以做些什么来让所有其他模块在初始化之前等待配置加载吗?如果不是,它基本上违背了运行时配置的目的。

最佳答案

我最近遇到了您遇到的问题。不幸的是,您可能已经知道,APP_INITIALIZER 不会阻止模块的导入。您可以使用全局窗口对象来附加您的配置数据。这样,数据就可以在您的应用程序中全局访问。

public loadConfig() {
return this._http.get('./assets/app-config/config.json')
.toPromise()
.then((config: any) => {
window['appConfigData'] = config;
this.config = config;
})
}

在属于 SharedModule 的服务中,您可以简单地从窗口对象访问配置数据。

constructor() {
..
..
const configData = window['appConfigData'];
}

关于angular - APP_INITIALIZER 不阻止导入的模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52544034/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com