繁体   English   中英

在执行下一个函数 Angular 之前强制等待一个函数

[英]Force wait a function before the execution of next function Angular

我想在执行之前等待一个函数。 我该怎么做呢

openOrganizationDialog(): void {
    const dialogRef = this.dialog.open(NewOrganizationComponent, {
      width: '800px',
      height: '600px',
      data: {
        view: 'dialog'
      }
    });
    dialogRef.afterClosed().subscribe(async result => {

      // Want to wait on below line, so that my list gets updated

      await this.getOrganizations();
      let organizationPreSelectId = this.organizationList[0].orginizationId;
      this.newLoanForm.patchValue({
        orginizationId: organizationPreSelectId
      });

    });
  }

这是我正在谈论的功能

async getOrganizations() {
    await this.organizationService.getOrganizations().subscribe((response) => {
      this.organizationList = response;
      this.organizationList.sort((a, b) => (a.orginizationId < b.orginizationId) ? 1 : -1);
    });
  }

我已经尝试过async await但它不起作用。 在此先感谢您的帮助。

您需要将 observable 转换为 promise,以便它等待。

async getOrganizations() {
    this.organizationList = await this.organizationService.getOrganizations().toPromise();
    this.organizationList.sort((a, b) => (a.orginizationId < b.orginizationId) ? 1 : -1);
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

https://www.learnrxjs.io/operators/utility/topromise.html

暂无
暂无

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

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