gpt4 book ai didi

angular - 如何在 RxJS 中使用 await

转载 作者:行者123 更新时间:2023-12-01 12:05:02 24 4
gpt4 key购买 nike

我是 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com