[英]Angular Conditionally Load Modules depending on custom service
我有一个关于如何在 Angular 8 App 中有条件地加载模块的问题。 由于我在 Angular 中完全是新手,所以我尝试在这里进行在线模拟
在那里我有一个自定义服务,它在现实生活中的应用程序中从json
文件中读取,但在这里我对其进行了硬编码:
export class AppConfigService {
private appConfig: any;
constructor(private http: HttpClient) {}
loadAppConfig() {
this.appConfig = {
components: {
integrity: false,
control: true
}
};
}
//GENERAL
get integrityVisible(): boolean {
return this.appConfig.components.integrity;
}
get controlVisible(): boolean {
return this.appConfig.components.control;
}
}
在我的 app.module.ts 我读了这个配置:
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, AppRoutingModule, LayoutsModule, HttpClientModule],
providers: [
{
provide: APP_INITIALIZER,
multi: true,
deps: [AppConfigService],
useFactory: (appConfigService: AppConfigService) => {
return () => {
return appConfigService.loadAppConfig();
};
}
}
],
bootstrap: [AppComponent]
})
然后我有一个名为IntegrityModule
的模块,我想根据AppConfigService
integrationVisible integrityVisible()
function 返回的值加载它。
导入发生在PagesModule
中:
@NgModule({
declarations: [],
imports: [
CommonModule,
FormsModule,
PagesRoutingModule,
ReactiveFormsModule,
IntegrityModule
]
})
这个问题的答案是我需要的,但不完全是,因为我想加载它,然后能够导航到它的组件和子组件。
本文是一些解决方法,它与CanLoad
一起使用,但我希望不创建IntegrityModule
,不创建也不能够加载。
所有这一切的重点是,我想在加载IntegrityModule
时进行一次 api 调用,并加载一些与此模块相关的信息,我希望这些信息对于此模块的所有组件都是全局的。 例如,如果我想在APP_INITALIZER
中加载此信息,并且 api 已关闭或无响应,则整个应用程序将无法加载。
有人可以建议完成这种行为的最佳方法是什么?
提前致谢,
朱利安
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.