angular - 如何在 RxJS 中使用 await

标签 angular async-await rxjs observable

我是 RxJS 的新手

这是我的功能

getData(id): Observable<any> {

    let accessToken = this.getAccessHeader();

    if (!accessToken) {
        // Here I want to wait till following observable completes, and returns value. Till then do not call next line methods i.e. code outside the if block

        this.getTemptoken().subscribe((res) => {
            accessToken = res.result.accessToken,
        });
    }
    const httpOptions = {
        headers: new HttpHeaders({
            'accessToken': accessToken
        })
    };
    return this.http.post(
        url,
        {
            'id': id
        }, httpOptions
    ).pipe(map((res) => {
        return res;
    }));
}

getTemptoken 也是一个可观察的,类似的函数,它调用 API 并返回 token 。我想等到 getTemptoken 返回值,然后只执行下一行,即下面的代码 if block

最佳答案

要在后续可观察对象中使用第一个可观察对象的结果,您可以在管道中使用 switchMap,例如:

of("Hello").pipe(
            switchMap(result => of(result + ", World")),
            switchMap(result => of(result + "!")),
          )
          .subscribe(console.log);
// output: Hello, World!

learnrxjs switchmap


如果您不需要前一个 observable 的结果,只想按特定顺序触发 observable,您可以使用 concat 等待每个 observable 完成后再触发下一个 observable:

concat(
  of(1).pipe(delay(2000)),
  of(2).pipe(delay(500)),
  of(3).pipe(delay(1000))
)
.subscribe(console.log);

// output: 1 2 3

learnrxjs concat


此外,您还可以使用 toPromise(),但它是一种反模式。看看

RxJS Observable interop with Promises and Async-Await

例如:

const source$ = Observable.interval(1000).take(3); // 0, 1, 2
// waits 3 seconds, then logs "2".
// because the observable takes 3 seconds to complete, and 
// the interval emits incremented numbers starting at 0
async function test() {
  console.log(await source$.toPromise());
}

learnrxjs topromise

关于angular - 如何在 RxJS 中使用 await,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58216233/

相关文章:

javascript - 如何使一个可观察对象依赖于另一个可观察对象

angular - cdkPortal 与 ngTemplateOutlet 有何不同

javascript - ng-bootstrap 下拉菜单和下拉菜单放置在同一页面中

angularjs - 直接绑定(bind)到 value 属性而不是 ngModel

angular - 我应该在 AngOnDestroy 中的 nexted 之后完成我的主题吗

http - 在多个位置的 http 调用的开始和结束处设置变量

angular - 如何在 Angular 2 中有条件地添加动画

javascript - 在异步等待中更新值

c# - Task.WaitAll() 没有按预期工作

Javascript - 类型错误 : x is not a function at done