我需要同时执行HttpClient
个GET请求,所以我在网上找到了一个解决方案,用toPromise
代替订阅,然后等待.
然而,我注意到this.form = = this.formBuilder.group
行代码在myAccount
被async
调用初始化之前执行.
换句话说,我预计执行代码将阻塞,直到this.myAccount
被初始化,然后开始执行this.form = this.formBuilder.group
行.
我理解的Async/AWait中的Java脚本是否正确.我需要做什么来实现我想要的--即,等待执行,直到this.myAccount
被调用await this.accountService.getById(this.id).toPromise()
初始化.
ngOnInit(): void {
this.getByIdSynchronously();
this.form = this.formBuilder.group({
scheduledDate: ['', Validators.required],
required: [''],
userAvailability: [''],
});
}
async getByIdSynchronously()
{
this.myAccount = await this.accountService.getById(this.id).toPromise();
}
我还有一个html页面,第一行代码如下所示:
<form [formGroup]="form" (ngSubmit)="onSubmit()" *ngIf="!isAdmin">
...
</form >
其中,isAdmin是本地函数:
get isAdmin()
{
if(this.myAccount)
{
return this.myAccount.role == Role.Admin;
}
else{
return true;
}
}
在我的异步/等待方法完成之前,它会执行十几次,所以我必须返回一些人为的真值,直到我的this.myAccount
被初始化.
Note个
我已经找到了第一个问题的解决方案--只需使用then
运营商的promise .我找不到第二个问题的解决方案--在this.myAccount
被初始化之前停止从模板html调用isAdmin
.对此有什么补救措施吗?