angular - 等待角度的异步操作
问题描述
在下面的代码片段中,如何等待异步操作完成然后执行循环?
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;
}
}
}
解决方案
将 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(...)
});
推荐阅读
- c# - 如何从 3 个输入中生成一个数字
- node.js - 在反应中为ckfinder设置服务器目录
- python - 在 Pandas/Jupyter 中使用日期和时间列作为 DatetimeIndex?
- matlab - 我想用matlab制作一个csv文件,但我的csv很奇怪
- javascript - 创建 ISO 格式的 UTC 时间戳
- javascript - 反应 axios 试图发送数据对象和图像文件,但服务器不会读取文件
- javascript - 无法将数据推送到 FormArray 中的 mat-table 并且该表单处于循环中所以我有多个表单每个表单都有一个 mat-table
- python - Python 在新列数据框中生成 16 个随机数字和字母
- reactjs - DatePicker react-datepicker 不读取 NVDA 中的日期,宣布空白
- embedded - Avrdude 无法使用 usbasp 检测到 mcu