【问题标题】:Rxjs concat Observable with conditionRxjs 连接 Observable 条件
【发布时间】:2021-12-09 13:36:55
【问题描述】:

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

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

我需要在每种情况下都进行搜索,但如果令牌无效,我需要先获取新令牌。 有没有办法在没有冗余代码的情况下做到这一点? 谢谢

【问题讨论】:

  • 如果你在你的应用中使用HTTPinterceptor来检查、验证和setToken会更好。

标签: angular rxjs


【解决方案1】:

一种方法可能如下:

    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 => {
             ...
      });

【讨论】:

  • 我尝试了您的解决方案,它有效。谢谢!
【解决方案2】:

看起来你正在做的事情依赖于你没有明确管理的一些状态。这很好,但在像 RxJS 这样的声明性库中,它总是看起来有点尴尬。你需要令牌,但我马上ignoreElements

这对你来说可能读起来很奇怪,但这样的东西应该可以工作:

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

【讨论】:

    猜你喜欢
    • 2023-01-30
    • 1970-01-01
    • 2017-03-09
    • 2020-07-16
    • 1970-01-01
    • 1970-01-01
    • 2020-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多