繁体   English   中英

如何使用异步等待订阅 angular

[英]How to use async await with subscribe angular

我正在调用 createOtherKind() function 并尝试使用 this.listKinds 的值。 我的问题是 isKindOtherCreated 没有等待 this.getKinds() 完成并且 this.listKinds 未定义。

我该怎么做?

代码:

  getKinds(): void {
    this.detailsService.getKinds().subscribe(async response =>{
      this.listKinds = await response.body;
    })
  }

  async createOtherKind() {
    await this.getKinds();
    const isKindOtherCreated = this.listKinds.find(kind => kind.name === "Other");

    if(!isKindOtherCreated) {
      this.createdKind.name = "Other";
      this.createKind();
    }
  }

您可以在createOtherKind()方法中调用getKinds()方法。 这就是您从this.listKinds变量中获取值的方式。 subscribe是异步方法。 因此,它不等待响应。

这是示例:

getKinds(): void {
    this.detailsService.getKinds().subscribe(async response =>{
      this.listKinds = response.body;
      await this.createOtherKind();
    })
  }

async createOtherKind() {
    const isKindOtherCreated = this.listKinds.find(kind => kind.name === "Other");

    if(!isKindOtherCreated) {
      this.createdKind.name = "Other";
      this.createKind();
    }
  }

问题正在发生,因为您将 Observables(您订阅的地方)与 async/await 混合在一起。 如果你想坚持使用承诺,你可以将你的getKinds function 修改为这样的:

  getKinds(): void {
    // Convert your observable to a Promise so you can use `await` on it
    return this.detailsService.getKinds().toPromise().then((response) => {
      this.listKinds = await response.body;
    });
  }

有关更多详细信息,我建议您查看这个类似的问题

你在这里使用订阅,所以我猜this.detailsService.getKinds()返回一个 observable。 您可以使用它进行制作,然后将其返回以便能够在代码的另一部分订阅其他内容。 喜欢:

getKinds(): Observable<any> {
    let myObs = this.detailsService.getKinds(); //Getting your observable

    //Reading result
    myObs.subscribe(response => {
      this.listKinds = response.body;
    });

    //Returning it to use it somewhere else
    return myObs;
  }

createOtherKind() {
    //Make request and subscribe to observable
    this.getKinds().subscribe( res => {
        const isKindOtherCreated = this.listKinds.find(kind => kind.name === "Other");

        if(!isKindOtherCreated) {
          this.createdKind.name = "Other";
          this.createKind();
       }
    }
  }

编辑

正如 Andres2142 所说,订阅两次并不是正确的行为方式。 它应该可以工作,但结果并不完全稳定,最好的方法是用水龙头 pipe 替换第一个订阅,因为它旨在执行副作用。 所以更好的答案是:

getKinds(): Observable<any> {
    return this.detailsService.getKinds()
        .pipe(
            tap( (response) => {
                this.listKinds = response.body;
            })
        );
  }

// createOtherKind() Doesn't need to change

暂无
暂无

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

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