Rxjs将Observable与条件连接



我正试图根据一个条件执行一个rest调用。调用将被执行,但根据情况,它将在另一个rest调用之后执行。目前,我尝试过这种方式,但我确信这不是最好的方式:

if(!checkTokenValidation()) {
this.service.getToken().pipe(
map(response => {
setToken(response);
})
).subscribe(() => {
this.service.search().subscribe(data => {
...
})
})
} else {
this.service.search().subscribe(data => {
...
})  
}

我需要在每种情况下进行搜索,但如果令牌无效,我需要首先获得新的令牌。有没有一种方法可以在没有多余代码的情况下做到这一点?感谢

一种方法可以是:

import { EMPTY, of } from "rxjs";
import { map, tap, switchMap } from "rxjs/operators";

// if token is valid, create an empty observable, else set the observable to the service.getToken api call
var obs$ = checkTokenValidation() ? of(EMPTY) : this.service.getToken().pipe(map(response => setToken(response));
// take the first observable and then map it to a new observable, a.k.a. the response from the service.search api call
obs$.pipe(switchMap(() => this.service.search())
.subscribe(data => {
...
});

您所做的工作似乎依赖于某些未明确管理的状态。这很好,但在RxJS这样的声明性库中,它看起来总是有点尴尬。你需要代币,但我立即ignoreElements

这可能读起来很奇怪,但像这样的东西应该会起作用:

( checkTokenValidation() ?
EMPTY :
this.service.getToken()
).pipe(
tap(response => setToken(response)),
ignoreElements(),
concatWith(this.service.search())
).subscribe(data => {
// ...
});

最新更新