【发布时间】:2019-04-06 08:00:07
【问题描述】:
我搜索了很多关于如何等待异步然后在 angular7 中执行同步,但到目前为止没有运气。 在我的组件中,我有两个方法 loadList() simpleMethod_1()。
点击事件触发 simpleMethod_1() 然后调用 loadList()
我尝试使用 angular async-await,但没有用,或者可能是我没有以正确的方式配置它! 我还尝试设置计时器,它按照我想要的方式工作(第 7-10 行执行),但是当互联网非常慢时它就会失败。
loadList() {
this.loadingGif = true;
this.service.resetAllStoredData();
// get the list data from server
this.service.getAllList().subscribe(list => {
this.list = list;
// save the list so as to retrieve again
this.service.setList(list); //sync
this.loadingGif = false;
});
}
simpleMethod_1(){
1. const storedId = this.localStroageService.getStoredId();
2. this.loadList();
3. console.log("aap loading 1", this.loadingGif)
4. if (
storedId !== null &&
storedId !== undefined
) {
5. console.log("aap loading 2", this.loadingGif)
6. if (!this.loadingGif) {
// check before navigating
7. const data = this.list.find(item => item.id === storedId );
8. if (!data.complete) {
// remember to store routing info
// fetch user data
9. this.getUserDetails();//synchronous
10. this.router.navigate("somepath")
}
}//end of loadingGif if
}
}//end of method
(注意:我特意给出了数字,以便指出我在说什么)
问题: 每当调用 simpleMethod_1() 时会发生什么,在第 1 行之后,异步方法 loadList() 被调用,第 3-5 行甚至在 loadList() 完成执行之前被执行!并且因为 loadingGif 仍然为真,所以第 7-10 行永远不会执行。
我想要实现的是,simpleMethod_1() 会被触发, - 第 1 行执行, - 应该调用 loadlist() 并等到它完成然后从那里出来 - 然后执行第 3、4、5、6、7、8、9、10 行 ...最后它应该导航到不同的页面
谁能建议我如何实现这一目标?
【问题讨论】:
标签: typescript asynchronous angular7 synchronous