angular - 如何等待服务准备好Angular?
问题描述
内部根组件初始化了第一次单音服务。
export class AppComponent {
constructor(private reonMapLibraryService: ReonMapLibraryService) {
}
}
然后在子组件中,我尝试准备好实例:
export class SearchFilterComponent implements OnInit, AfterViewInit {
constructor(private reonMapLibraryService: ReonMapLibraryService) {}
ngAfterViewInit(): void {
this.layers = this.reonMapLibraryService.layersManager.getRegistryTree();
}
}
它说reonMapLibraryService
是undefined
,因为首先加载了子组件。
如何等待子组件的服务?
解决方案
如果您需要在应用程序初始化之前等待准备就绪的服务或异步预取一些数据,那么最好的地方是APP_INITIALIZER。应用程序应在初始化程序执行期间等待,并且仅在初始化程序解决后才会启动。您可以像这样使用它(让我们将初始化程序放在 AppModule 中):
export function init_app(reonMapLibraryService: ReonMapLibraryService) {
return async () => await reonMapLibraryService.fetchData();
}
@NgModule({
declarations: [...],
imports: [...],
providers: [
...,
ReonMapLibraryService,
{
provide: APP_INITIALIZER,
useFactory: init_app,
deps: [ReonMapLibraryService],
multi: true
}
]
})
而已。它应该等待fetchData
方法执行并仅在解决后引导应用程序。
推荐阅读
- activemq - activemq 多消费者多主题性能
- mysql - 如何从 MySQL json(或文本)列中查找特定值?
- google-apps-script - 如何将应用程序脚本函数值(字符串)作为 importXML 函数直接传递给谷歌工作表单元格?
- javascript - 完全按照在 DOM 中设置的元素的小数像素获取 CSS 顶部值
- business-intelligence - 2 个提示日期之间的总天数(SAP Business Object Intelligent Rich Client)
- azure - 如何使用 datafactory 从 RestAPI 复制数据并将其保存在 Datalake 中?
- angular - 我想将数据库的 creado_por 字段显示为字符串
- reactjs - 反应顶点饼图不显示标签
- javascript - 如何将 ScrollView 转换为 FlatList
- node.js - 抱歉,名称不能包含前导或尾随空格,并且名称只能包含 URL 友好字符