我想与forkJoin一致地安排多个可观测对象,但是想分别订阅它们,如下所示。
const ox = http.get('x');
const oy = http.get('y');
const all = interval(1000).pipe(
switchMap(
() => forkJoin(ox, oy)
);
);
// component x
const sx = ox.subscribe((x) => { showX(x); });
// component y
const sy = oy.subscribe((y) => { showY(y); });
// Another component
const sAll = all.subscribe(([x, y]) => { doStuffThatNeedsBothXY(x, y); });
什么是最好的方法?我想保持ox
和oy
的类型为“可观察”,而不是在tap
使用其他技术,例如管道副作用(all
)。
答案 0 :(得分:0)
似乎不必订阅每个单独的流并同时订阅两者。
您可以执行以下操作:
sAll = combineLatest(this.toDos$, this.posts$)
.pipe(
tap(([todos, posts]) => {
this.todos = todos;
this.posts = posts;
})
)
.subscribe(() => console.log("subscribe"));
使用combineLatest
自动订阅每个流和,使您可以同时访问这两个流。
注意:如果您订阅ox并订阅ox和另一个流的组合,则将订阅该流两次,并第二次发出HTTP请求。您可以在我的示例Stackblitz中尝试一下。
我在这里有一个Stackblitz示例:
https://stackblitz.com/edit/angular-todos-posts-noasynpipe-deborahk
或者用您的变量查看它:
sAll = combineLatest(ox, oy)
.pipe(
tap(([x, y]) => {
showX(x);
showY(y);
doStuffThatNeedsBothXY(x,y);
})
)
.subscribe(() => console.log("subscribe"));
如果这不符合您的要求,那么您是否可以针对需要全部三个订阅的用例进行具体说明?