【问题标题】:Combing an Observable result with an existing RxJS Subject without subscribe在没有订阅的情况下将 Observable 结果与现有的 RxJS 主题结合起来
【发布时间】:2020-01-13 18:08:54
【问题描述】:

我有一个现有的 rxjs 主题。我想做的是调用另一个 Observable 并将该 observable 的结果“下一个”到主题中。如果可能的话,我希望能够在不调用 subscribe 的情况下获得子 Observable 的值。

不幸的是,Subscribe.next() 需要一个值。直接在主题上使用 switchMap 也不起作用(switchMap 和 child 调用永远不会触发)。

// init subject in class definition
mySubject$ = new Subject();

// call api and observable
callApi(options) {
   // get an observable from the api call
   const apiResults$ = getApiResults(options);

   // this works but requires an subscribe
   apiResults$.subscribe(results => this.mySubject$.next(results));

   // how to combine the results into the Subject without 
   // the subscribe method (above)
   mySubject$.next(????);
}

【问题讨论】:

  • 你必须订阅,否则你怎么知道 api observable 何时发出值?您可以使用 apiResults$.subscribe(this.mySubject$);作为一个主题既是观察者又是可观察者。

标签: typescript rxjs


【解决方案1】:

如果您试图让某种可观察的事件来监听 api 调用,那么有更好的方法。

您应该返回带有 tap 副作用的 api 调用 observable,该副作用会触发主题发出结果。

mySubject$ = new Subject();

callApi(options) {
   return getApiResults(options).pipe(tap(res=>mySubject$.next(res)));

}

【讨论】:

  • rest 未定义。你的意思是.next(res)
  • 谢谢,我试试看
猜你喜欢
  • 2020-09-28
  • 1970-01-01
  • 2017-10-10
  • 2020-06-09
  • 2018-10-13
  • 2021-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多