我创建了一个从配置文件加载属性的服务,但我不知道如何在模块定义类中使用它。
您不能使用 Angular 服务,因为这需要初始化注入器。这ngModule需要配置beforeAngular 中的任何内容都已启动。
The root模块被加载plaformBrowserDynamic().bootstrapModule(AppModule)
你的代码行main.ts
文件。这是 Angular 中一切事物开始的地方。
您只需要在执行这行代码之前加载您的配置即可,并且不存在延迟此操作的技术问题。引导程序中此步骤的异步操作将显示空白页面,直到操作完成,这会导致用户体验不佳。
我可以通过改变来演示效果main.ts
至以下内容:
(function () {
return new Promise(resolver => {
window.setTimeout(() => resolver(), 5000);
});
})().then(() => {
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.log(err));
});
上面的代码只是将 Angular 的引导延迟了 5 秒。
这是为什么您不应该在应用程序启动时异步加载资源的一个很好的理由,但如果您真的想这样做,那么它没有理由不起作用。
您需要更改承诺,以便它解析为您需要的配置设置,然后将其传递给您的静态函数AppModule
.
我将更新我的示例,但假设您的最终源代码正在对远程配置文件发出 HTTP 请求。
(function () {
return new Promise(resolver => {
const exampleConfig = {
options: 'ABC'
};
window.setTimeout(() => resolver(exampleConfig), 5000);
});
})().then(config => {
platformBrowserDynamic().bootstrapModule(AppModule.withConfig(config))
.catch(err => console.log(err));
});
您现在必须手动创建模块定义AppModule
,但这与模块的实现方式完全相同forRoot()
方法。我刚刚将其重命名为withConfig()
所以听起来更好。
@NgModule()
export class AppModule {
static withConfig(config: any): ModuleWithProviders {
return {
ngModule: AppModule,
imports: [
MqttModule.forRoot(config)
]
};
}
}
我强烈建议后端服务器将所需的配置数据注入到index.html
这样就不需要异步操作。然后您可以在中引用全局变量AppModule
并跳过withConfig()
步。这server应该负责引导程序stateAngular 应用程序的一部分。