我正在構建一個Angular2應用程序,並且有兩個BehaviourSubjects
,我想將它們合併爲一個訂閱。我提出了兩個http請求,並且希望在兩人都回來時發起一個事件。我在看forkJoin
vs combineLatest
。看起來combineLatest會在任何一個behvaviorSubjects被更新時觸發,而forkJoin只會在所有behaviorsSubjects被更新後觸發。它是否正確?必須有一個普遍接受的模式,這不是嗎?如何合併多個rxjs BehaviourSubjects
編輯
這裏是我的angular2組件訂閱我的behaviorSubjects的一個示例:
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);
}
})
});
}
}
這裏是我的組件的訂閱的一個片段:
this._cpmService.cpmSubject.subscribe(cpmList => {
doSomeWork();
});
但是相反在單個訂閱上觸發doSomeWork()我只想在cpmSubject和fooSubject觸發時觸發doSomeWork()。
一個http請求不能直接返回'BehaviorSubject' - 我猜想,你是'nexting' HTTP的響應每到一個'BehaviorSubject'或者甚至訂閱'Subject'到'get/post/put'? – olsn
@olsn是的,我訂閱了http響應,並將我的主題與他們在服務類中的回覆聯繫起來 – cobolstinks
行爲主題的公共訪問是反模式。請使用帶有「as Observable」的downcast的getter。所以你不能使用服務外的下一個電話 - >分離問題 –