在执行下一行之前保证观察到的响应

时间:2018-10-04 12:04:34

标签: angular typescript rxjs observable

我试图等待可观察到的API调用,然后再继续执行下一行代码/功能。我无法执行此操作,但是诺言可以等待。 到目前为止,这是我的代码:

 async validateDataObservable(email: string) {
    await this.userProfileService.getUserByEmail().subscribe((val: any) => {
      console.log('Hello');
    });
    console.log('Execute after Hello');

    // Output:
    // Execute after Hello
    // Hello
  }

不幸的是,这不是理想的输出行为。

下面的代码可以工作,但是由于需要,我需要Observable的功能相同。

  async validateDataPromise(email: string) {
    await this.userProfileService.getUserByEmailPro(email).then((val: any) => {
      console.log('Hello');
    });
    console.log('Execute after Hello');

    // Output:
    // Hello
    // Execute after Hello
  }

感谢您的帮助。 谢谢

3 个答案:

答案 0 :(得分:0)

await是一个Promise功能,因此遗憾的是您无法使用Observables做到这一点。如果确实需要此功能,则可以使用.toPromise(),但不建议这样做。您应该将代码放在subscribe主体内(或map内)。

答案 1 :(得分:0)

您可以使用行为/异步主题并完整编写代码。如下所示:

validateDataPromise(email: string) {
  this.userProfileService.getUserByEmailPro(email)
  .takeUntil(this.unSub)
  .subscribe((val: any) => {
    console.log('Hello');
  }, (error: Error) => {
    console.error('Error');
  }, () => {
    console.log('Execute after Hello');
  });
}

参考: https://medium.com/@luukgruijs/understanding-rxjs-behaviorsubject-replaysubject-and-asyncsubject-8cc061f1cfc0

http://reactivex.io/rxjs/manual/overview.html#asyncsubject

答案 2 :(得分:-1)

您不能那样做。将其余代码(要在console.log('hello')之后执行的代码)获取到函数。并在调用后在subscribe中调用该函数 console.log('hello')。或者,您也可以将其余代码放在console.log('hello)之后的订阅中。

async validateDataPromise(email: string) {
    await this.userProfileService.getUserByEmailPro(email).then((val: any) => {
      console.log('Hello');
      this.doRest()
    });


    // Output:
    // Hello
    // Execute after Hello
  }

doRest(){
  console.log('Execute after Hello');
 // implement what you want after asynchronous call.
}