我尝试使用 concatmap 并按顺序完成可观察数据,当 queryParams 有 id 时,它应该只调用 getbearer token ,否则它应该使用 securekey 导航到错误,但实际上它会使用 bearer-token 进入错误页面
const result = this.activatedRoute.queryParams.pipe(
concatMap((params) => {
if (params.hasOwnProperty('id')) {
sessionStorage.setItem('secureKey', params.id);
return this.httpServiceService.getBearerTokens();
} else {
this.router.navigate(['error'], {
queryParams: { 'error-key': 'secure-key' },
});
}
})
);
result.subscribe(
(response: any) => {
if (response.access_token) {
sessionStorage.setItem('bearerToken', response.access_token);
this.router.navigate(['summary']);
} else {
this.router.navigate(['error'], {
queryParams: { 'error-key': 'bearer-token' },
});
}
},
(error) => {
this.router.navigate(['error'], {
queryParams: { 'error-key': 'bearer-token' },
});
}
);
最佳答案
我认为
concatMap
只是要求竞争条件(但我不知道查询参数更改的频率和容易程度)。我会使用switchMap
来代替,因为我想象当我们从"?id=alice"
导航到"?id=bob"
时,爱丽丝的代币问题变得无关紧要。通常,有条件地订阅另一个流应该可以与
switchMap
和filter
配合使用:
firstStream$.pipe(
filter(result => someCondition(result)),
switchMap(result => getAnotherStream(result))
).subscribe(//...
哦,顺便说一句,您的 concatMap
仅返回一个流 if (params.hasOwnProperty('id'))
。这甚至可以编译吗?在 else
分支中也返回一个 observable,它甚至可能是 EMPTY
,但可能应该是 throwError
。
关于javascript - 如何在第一个可观察值成功时有条件地订阅另一个可观察值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60209090/