【发布时间】:2019-03-09 19:39:09
【问题描述】:
我正在尝试等待来自 observable 的 API 调用,然后再继续执行下一行代码/函数。我无法做到这一点,但是 promise 可以与 await 一起使用。 到目前为止,这是我的代码:
async validateDataObservable(email: string) {
await this.userProfileService.getUserByEmail().subscribe((val: any) => {
console.log('Hello');
});
console.log('Execute after Hello');
// Output:
// Execute after Hello
// Hello
}
不幸的是,这不是所需的输出行为。
下面的代码可以工作,但由于需要,我需要 Observables 相同的功能。
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
}
感谢任何帮助。 谢谢
【问题讨论】:
-
您不能将
console.log('Execute after Hello');行放在then()函数中吗?那么它总是在第一个函数之后执行。 -
最简单的方法是在
subscribe回调中移动console.log('Execute after Hello'),紧跟在console.log('Hello')之后。 -
你可以使用
toPromise(),但这意味着源 Observable 必须完成。
标签: angular typescript rxjs observable