我在谷歌上搜索了很多关于如何等待异步,然后在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()都会被调用,并且在loadList()完成执行之前就会执行第3-5行!因为loadingGif仍然是真的,所以第7-10行永远不会执行。
我想要实现的是,simpleMethod_1()将被触发,-第1行执行,-应该调用loadlist()并等待它完成,然后从那里-and出来,然后执行第3,4,5,6,7,8,9,10行...at结束它应该导航到不同的页面
有谁能建议我怎样才能做到这一点?
发布于 2019-04-05 22:50:00
这里有一个解决方案
async simpleMethod1()
{
await this.loadList()
}
async loadList() {
var result = await this.service.getAllList();
}
async getAllList(): Promise<any>
{
this.httpService.get().toPromise()
}发布于 2019-04-06 07:59:33
我用管道和水龙头解决了这个问题,发布了答案,以防任何人觉得这有帮助。
loadList(): Observable<something[]> {
this.lodingGif = true;
// get the list data from server
return this.service.getAllList().pipe(
tap(list => {
// statement..
//statement..
});
}
simpleMethod_1(){
this.loadList()
.toPromise()
.then(list => {
1. statement...
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) {
// fetch user data
9. this.getUserDetails();//synchronous
10. this.router.navigate("somepath")
}
}//end of loadingGif if
}
});
}//end of methodhttps://stackoverflow.com/questions/55520477
复制相似问题