【发布时间】:2017-03-16 17:25:07
【问题描述】:
我正在构建一个 Angular2 应用程序,并且有两个 BehaviourSubjects 我想在逻辑上合并为一个订阅。我正在发出两个 http 请求,并希望在它们都回来时触发一个事件。我正在查看 forkJoin 与 combineLatest。似乎 combineLatest 会在任何一个 behvaviorSubjects 更新时触发,而 forkJoin 只会在所有 behavoirSubjects 都更新后触发。它是否正确?必须有一个普遍接受的模式,不是吗?
编辑
这是我的 angular2 组件订阅的其中一个行为主题的示例:
export class CpmService {
public cpmSubject: BehaviorSubject<Cpm[]>;
constructor(private _http: Http) {
this.cpmSubject = new BehaviorSubject<Cpm[]>(new Array<Cpm>());
}
getCpm(id: number): void {
let params: URLSearchParams = new URLSearchParams();
params.set('Id', id.toString());
this._http.get('a/Url/Here', { search: params })
.map(response => <Cpm>response.json())
.subscribe(_cpm => {
this.cpmSubject.subscribe(cpmList => {
//double check we dont already have the cpm in the observable, if we dont have it, push it and call next to propigate new cpmlist everywheres
if (! (cpmList.filter((cpm: Cpm) => cpm.id === _cpm.id).length > 0) ) {
cpmList.push(_cpm);
this.cpmSubject.next(cpmList);
}
})
});
}
}
这是我的组件订阅的 sn-p:
this._cpmService.cpmSubject.subscribe(cpmList => {
doSomeWork();
});
但我不想在单个订阅上触发 doSomeWork(),我只想在 cpmSubject 和 fooSubject 触发时触发 doSomeWork()。
【问题讨论】:
-
http-request 不能直接返回
BehaviorSubject- 我假设你是nextinghttp-responses 每个都变成BehaviorSubject或者甚至可能订阅Subject到get/post/put? -
@olsn 是的,我正在订阅 http 响应,并在我的主题下一个他们在服务类中的响应
-
行为主体的公共访问是一种反模式。请使用带有“as Observable”的向下转换的吸气剂。所以不能在服务外使用下一个调用->关注点分离
标签: rxjs behaviorsubject