我在Angular2应用程序中使用NGRX和RxJS。当使用尝试保存记录更新时,我生成一个动作'UPDATE',我想调用API来更新数据库。
问题是“.filter(action => action.type == UPDATE)”之后的所有内容都会被调用4次。
我不明白为什么。我尝试了很多东西和代码更改,但问题仍然存在......
我的代码:
private actions$ : BehaviorSubject<Action> = new BehaviorSubject<Action>({type: null, payload: null});
.../....
// catch employee selection
let update = this.actions$
.filter ( action => action.type==UPDATE )
// **** following are executed 4 times ****
.do( () => this._store.dispatch({type: REDUCER_UPDATING }) )
.mergeMap ( action =>this._APIService.updateEmployee(action.payload) ); //
// merge all stream and dispatch action
let all = Observable.merge (update, load, selectItem);
all.subscribe ((action:Action) => this._store.dispatch (action));
要查看直播问题:
https://plnkr.co/edit/zq4AsKJYILfrgItDNbHo?p=preview
在主面板中选择一名员工。在详细信息面板中,单击保存按钮。您将在控制台中看到API被调用4次:
REDUCER - {"type":"SELECTING_ITEM","payload":1}
REDUCER - {"type":"UPDATING"}
API - UPDATE_EMPLOYEE <====1
REDUCER - {"type":"UPDATING"}
API - UPDATE_EMPLOYEE <====2
REDUCER - {"type":"UPDATING"}
API - UPDATE_EMPLOYEE <====3
REDUCER - {"type":"UPDATING"}
API - UPDATE_EMPLOYEE <====4
REDUCER - {"type":"UPDATED"}
感谢您的帮助!!
答案 0 :(得分:2)
我将update
部分替换为:
// catch employee selection
let update = this.actions$
.filter ( action => action.type==UPDATE )
// **** following are executed 4 times ****
.do( () => this._store.dispatch({type: REDUCER_UPDATING }) )
.mergeMap ( action =>this._APIService.updateEmployee(action.payload) )
.share(); //
这导致日志中只出现一个更新。
您观察到更新重复的原因是因为每次订阅更新流时,可观察链都会“重新启动”。这就是RxJS中所谓的冷可观察性。解决方案很简单,只需在您想要在多个订阅者之间共享的observable末尾添加share
。
有关热与冷的详细信息,请参阅official documentation。您还可以查看illustrated data and subscription flows。