本文介绍了如何获得对状态树的访问? (@ ngrx/效果2.x)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在将 @ ngrx/effects 从1.x更新到2.x
I am updating @ngrx/effects from 1.x to 2.x
在1.x版本中,我实际上可以访问状态树:
In 1.x I have access of state tree in effect:
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中,它只给我动作.还有没有办法访问状态树?还是我应该避免这样使用,因为这不是一个好习惯?
Now in 2.x, it only gives me action. Is there still a way to get access of the state tree? Or should I avoid using like this because it is not a good practice?
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 }));
推荐答案
另一种方法是使用.withLatestFrom(this.store)
.因此,完整的代码是:
Another way is using .withLatestFrom(this.store)
. So the complete code is:
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 }));
这篇关于如何获得对状态树的访问? (@ ngrx/效果2.x)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!