繁体   English   中英

停止执行代码,直到我的 async/await HttpClient get 操作完成执行代码(包括 html 调用)

[英]Stop executing code until my async/await HttpClient get operation finishes executing code (including html calls)

我需要同步执行HttpClient获取请求,所以我在互联网上找到了使用toPromise而不是 subscribe 然后等待的解决方案。 但是我注意到this.form = = this.formBuilder.group代码行在myAccountasync调用初始化之前执行。 换句话说,我期望执行代码会阻塞,直到this.myAccount被初始化,然后开始执行this.form = this.formBuilder.group行。 我是否理解 javascript 中的 async/await 正确。 我需要做什么才能实现我想要的 - 也就是说,等待执行直到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 是本地 function:

get isAdmin()
  {
    if(this.myAccount)
    {
      return this.myAccount.role == Role.Admin;
    }
    else{
      return true;
    }
  }

它在我的 async/await 方法完成之前执行了几十次,所以我必须返回一些人为的真实值,直到我的this.myAccount被初始化。

笔记

我找到了第一个问题的解决方案 - 只需使用 Promise 的then运算符。 我找不到第二个问题的解决方案 - 停止从模板isAdmin调用 isAdmin 直到this.myAccount被初始化。 有补救措施吗?

你应该使用 Observables 而不是 Promises,因为 Angular 也鼓励使用 Observables。 HTTPClient 返回一个 observable,因此您可以订阅它。

账户服务

    getById(id: number): Observable<any> {
        return this.httpClient.get(`URL goes here. ID goes into PARAMS`);
    }

然后在您的组件中订阅您的 API 调用。 您可以使用另一个变量来阻止 isAdmin 被连续调用。

isLoaded: boolean = false;
ngOnInit(): void {
      this.accountService.getById(this.id).subscribe(resp=>{
          this.form = this.formBuilder.group({
          scheduledDate: ['', Validators.required],
          required: [''],
          userAvailability: [''] });
          this.isLoaded = true;
      });
}
<form [formGroup]="form" (ngSubmit)="onSubmit()" *ngIf="isLoaded && !isAdmin">
...
</form>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM