javascript - Ionic JavaScript 函数无需等待承诺即可执行
问题描述
我有以下在页面 ngOnInit 上调用的方法
ngOnInit() {
this.devicesinfo.fetchdata().then(response => {
this.deviceSub = this.devicesinfo.alldevices.subscribe(alldevices => {
this.deviceinfosarr = alldevices;
alert(JSON.stringify(this.deviceinfosarr[0]));
this.doneloading = true;
} );
});
}
这是设备信息服务类中的获取数据方法。
async fetchdata() {
return await new Promise((resolve, reject) => {
this.getuserdevicesIDs().then(response => {
alert(this.arrIDs.IDs+ ' IDs I have');
// get all of the IDS of the devices a user owns.
// tslint:disable-next-line: prefer-for-of
this.getdeviceinfo().then(res => { // Get the information of a specific device
const device = (res);
this.deviceinfos[0] = device;
});
});
resolve(true); // when you want to return a value in promise
});
// tslint:disable-next-line: prefer-const
// tslint:disable-next-line: no-var-keyword
}
我的目标是让 NgOnit 等待获取数据完成,然后再执行所有其他方法,但目前这些方法会立即触发,而获取数据仍然很忙。知道为什么会这样吗?
解决方案
当 Angular 加载组件时,它会运行不同的生命周期钩子(此处为官方文档)
在您的情况下,将在您需要更新代码以按顺序运行ngOnInit()
之前触发。fetchdata()
推荐阅读
- python - 在 lxml 树上使用 copy.deepcopy() 时的多次重复
- authentication - Keycloak:自定义用户存储提供程序在用户登录期间多次调用 getUserById
- javascript - 按钮在桌面上可以正常工作,但在移动设备上不起作用
- sql-server - 用户 'rpa' 登录失败。(18456) (SQLDriverConnect)")
- reactjs - EXPO:设置 react-native-action-sheet
- typo3 - TYPO3 通过typoscript lib 包含一个扩展
- environment-variables - ExpandEnvironmentStringsA() 字符串下标超出范围
- flutter - 颤振包:facebook_audience_network 不支持空安全:
- scala - Spark ML Word2Vec 的变换函数中的 wordIndices 和 offset 到底是什么?
- networking - 如何在 Docker Swarm 专用网络中使用 Traefik v2.x?