简体   繁体   English

如何使用异步等待订阅 angular

[英]How to use async await with subscribe angular

I'm calling createOtherKind() function and trying to use the value of this.listKinds.我正在调用 createOtherKind() function 并尝试使用 this.listKinds 的值。 My problem is that isKindOtherCreated is not waiting this.getKinds() to finish and this.listKinds is undefined.我的问题是 isKindOtherCreated 没有等待 this.getKinds() 完成并且 this.listKinds 未定义。

How can i do it?我该怎么做?

Code:代码:

  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();
    }
  }

You can call the createOtherKind() method inside getKinds() method.您可以在createOtherKind()方法中调用getKinds()方法。 This is how you will get the value from this.listKinds variable.这就是您从this.listKinds变量中获取值的方式。 subscribe is async method. subscribe是异步方法。 So, it does not wait for the reponse.因此,它不等待响应。

Here is Example:这是示例:

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();
    }
  }

The issue is happening because you're mixing Observables (where you have subscribe) with async/await.问题正在发生,因为您将 Observables(您订阅的地方)与 async/await 混合在一起。 If you want to stick to using promises you could revise your getKinds function to something like this:如果你想坚持使用承诺,你可以将你的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;
    });
  }

For more details, I recommend taking a look at this similar question .有关更多详细信息,我建议您查看这个类似的问题

You use subscribe here, so I guess this.detailsService.getKinds() returns an observable.你在这里使用订阅,所以我猜this.detailsService.getKinds()返回一个 observable。 You can make things with it then return it to be able to subscribe something else in another part of your code.您可以使用它进行制作,然后将其返回以便能够在代码的另一部分订阅其他内容。 like:喜欢:

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();
       }
    }
  }

EDIT编辑

As said by Andres2142, subscribe twice isn't exactly the right way to act.正如 Andres2142 所说,订阅两次并不是正确的行为方式。 It should work but the result isn't perfectly stable, the best way is to replace the first subscribe by a tap pipe since it is desinged to perform side-effects.它应该可以工作,但结果并不完全稳定,最好的方法是用水龙头 pipe 替换第一个订阅,因为它旨在执行副作用。 So a better answer is:所以更好的答案是:

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