首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在effects中访问状态树?(@ngrx/effects 2.x)

如何在effects中访问状态树?(@ngrx/effects 2.x)
EN

Stack Overflow用户
提问于 2016-09-19 05:15:47
回答 2查看 6.9K关注 0票数 23

我正在将@ngrx/效果从1.x更新到2.x

在1.x中,我有效地访问了状态树:

代码语言:javascript
复制
  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中,它只给了我一些行动。还有一种方法可以访问状态树吗?或者我应该避免这样使用,因为这不是一个好的做法?

代码语言:javascript
复制
  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 }));
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-09-19 15:29:58

另一种方法是使用.withLatestFrom(this.store)。所以完整的代码是:

代码语言:javascript
复制
  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 }));
票数 26
EN

Stack Overflow用户

发布于 2016-09-19 05:41:42

效果不必是类属性;它们也可以是方法。这意味着您可以访问注入构造函数的存储。

在撰写此答案时,我并不清楚属性声明和public/private构造函数参数的语义。如果属性是在构造函数之后声明的,它们可以访问通过构造函数参数声明的public/private成员,因此您不必将效果声明为函数。

对于注入的存储,您应该能够使用像mergeMap这样的操作符来获取状态,并将其与您收到的更新组合起来:

代码语言:javascript
复制
@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风格的选择器--听起来是合理的,但是如果您所需要的特定效果所需的所有信息都包含在它正在聆听的操作中,它就会更干净。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39565811

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档