7

是否可以在一个动作中访问不同的状态?

场景:我有两种状态:

  • 过滤器状态
  • 应用状态

FilterState包含一个 action Filter,当过滤器动作被触发时,然后使用filterServiceaction 的有效负载 + 调用AppState.

@Action(Filter)
filter(ctx, action) {
  // HOW TO GET VALUE FROM AppState

  return this.filterService.filter(action, valueFromOtherStore).pipe(
    tap(data => {
    // Do something with result
    })
  );
}

如何从不同的状态检索值以将此值应用于的第二个参数this.filterService.filter

4

2 回答 2

7

Shared State文档回答了这个问题:

要访问不同的状态selectSnapshot方法,store可以使用: this.store.selectSnapshot(PreferencesState.getSort)

例子

@State<PreferencesStateModel>({
  name: 'preferences',
  defaults: {
    sort: [{ prop: 'name', dir: 'asc' }]
  }
})
export class PreferencesState {
  @Selector()
  static getSort(state: PreferencesStateModel) {
    return state.sort;
  }
}
​
@State<AnimalStateModel>({
  name: 'animals',
  defaults: [
    animals: []
  ]
})
export class AnimalState {
​
  constructor(private store: Store) {}
​
  @Action(GetAnimals)
  getAnimals(ctx: StateContext<AnimalStateModel>) {
    const state = ctx.getState();
​
    // select the snapshot state from preferences
    const sort = this.store.selectSnapshot(PreferencesState.getSort);
​
    // do sort magic here
    return state.sort(sort);
  }
​
}
于 2018-07-16T10:44:42.510 回答
3

选择快照将返回未定义,因为尚未启动其他状态,我通过使用普通选择和过滤结果解决了这个问题。

@State<PreferencesStateModel>({
  name: 'preferences',
  defaults: {
    sort: [{ prop: 'name', dir: 'asc' }]
  }
})
export class PreferencesState {
  @Selector()
  static getSort(state: PreferencesStateModel) {
    return state.sort;
  }
}
​
@State<AnimalStateModel>({
  name: 'animals',
  defaults: [
    animals: []
  ]
})
export class AnimalState {
​
  constructor(private store: Store) {}
​
  @Action(GetAnimals)
  getAnimals(ctx: StateContext<AnimalStateModel>) {
    const state = ctx.getState();
​
    // select the snapshot state from preferences
    return this.store.select(PreferencesState.getSort)
    .pipe(
       filter(sort => sort !== undefined),
       take(1),
       map(sort => {
           // do sort magic here
           return state.sort(sort);
       })
    );
​
}
于 2018-11-22T20:57:55.990 回答