我正在将@ngrx/效果从1.x更新到2.x
在1.x中,我有效地访问了状态树:
constructor(private updates$: StateUpdates<AppState>) {}
@Effect() bar$ = this.updates$
.whenAction(Actions.FOO)
.map(obj => obj.state.user.isCool)
.distinctUntilChanged()
.filter(x => x)
.map(() => ({ type: Actions.BAR }));在2.x中,它只给了我一些行动。还有一种方法可以访问状态树吗?或者我应该避免这样使用,因为这不是一个好的做法?
constructor(private actions$: Actions) {}
@Effect() bar$ = this.actions$
.ofType(ActionTypes.FOO)
.map((obj: any) => {
console.log(obj); // here is action only
return obj.state.user.isCool // so it is wrong here
})
.distinctUntilChanged()
.filter(x => x)
.map(() => ({ type: ActionTypes.BAR }));发布于 2016-09-19 15:29:58
另一种方法是使用.withLatestFrom(this.store)。所以完整的代码是:
constructor(
private actions$: Actions,
private store: Store<AppState>
) {}
@Effect() bar$ = this.actions$
.ofType(ActionTypes.FOO)
.withLatestFrom(this.store, (action, state) => state.user.isCool)
.distinctUntilChanged()
.filter(x => x)
.map(() => ({ type: ActionTypes.BAR }));发布于 2016-09-19 05:41:42
效果不必是类属性;它们也可以是方法。这意味着您可以访问注入构造函数的存储。
在撰写此答案时,我并不清楚属性声明和public/private构造函数参数的语义。如果属性是在构造函数之后声明的,它们可以访问通过构造函数参数声明的public/private成员,因此您不必将效果声明为函数。
对于注入的存储,您应该能够使用像mergeMap这样的操作符来获取状态,并将其与您收到的更新组合起来:
@Effect()
bar$(): Observable<Action> {
return this.actions$
.ofType(ActionTypes.FOO)
.mergeMap((update) => this.store.first().map((state) => ({ state, update })))
.map((both) => {
// Do whatever it is you need to do with both.update and both.state.
return both.update;
})
.distinctUntilChanged()
.filter(x => x)
.map(() => ({ type: ActionTypes.BAR }));
}
}我想,做这件事是否是好做法是一个意见问题。阅读状态--最好是通过组成ngrx风格的选择器--听起来是合理的,但是如果您所需要的特定效果所需的所有信息都包含在它正在聆听的操作中,它就会更干净。
https://stackoverflow.com/questions/39565811
复制相似问题