首页 > 解决方案 > 等待角度的异步操作

问题描述

在下面的代码片段中,如何等待异步操作完成然后执行循环?

ngOnInit() {
       this.userService.query()
        .subscribe((res: HttpResponse<User[]>) => { this.users = res.body; }, (res: HttpErrorResponse) => this.onError(res.message));

    this.principal.identity().then((account) => {
        this.currentAccount = account;

    });

    //my loop 
    for ( const user of this.users){
        if (user.login === this.currentAccount.login){
            this.currentUserId = user.id;
        }
    }


}

标签: angularjhipster

解决方案


将 Promise 更改为 Observable,或者将 Observable 更改为 Promise,将它们全部解决,然后运行循环。

const c1 = this.userService.query().toPromise();
const c2 = this.principal.identity();
Promise.all([c1, c2]).then(([r1, r2]) => {
  for (...)
})

const c1 = this.userService.query();
const c2 = Observable.fromPromise(this.principal.identity());
Observable.forkJoin([c1, c2]).subscribe([r1, r2] => {
  for(...)
});

推荐阅读