ngxs:在Action中访问其他状态

时间:2018-07-16 09:31:08

标签: ngxs

是否可以在一个动作中访问其他状态?

场景: 我有两种状态:

  • FilterState
  • AppState

FilterState包含一个动作Filter,当触发筛选器动作时,将使用动作+的有效负载和filterService中的值来调用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的第二个参数?

2 个答案:

答案 0 :(得分:3)

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);
  }
​
}

答案 1 :(得分:0)

选择快照将返回不确定的状态,因为尚未启动其他状态,我已经通过使用常规选择并过滤结果来解决了这个问题。

@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);
       })
    );
​
}