其他分享
首页 > 其他分享> > [NGXS] Select - 3. @Selector orders matter

[NGXS] Select - 3. @Selector orders matter

作者:互联网

Problem:

// counter.state.ts
export interface CounterStateModel {
  counter: number;
}

@State<CounterStateModel>({
  name: 'counter',
  defaults: {
    counter: 0
  }
})
export class CounterState {}

// counter.query.ts
export class CounterQuery {
  @Selector([CounterQuery.getCounter])
  static getCounterCube(counter: number): number {
    return counter ** 3;
  }

  // Note: this selector being declared after its usage will cause an issue!!!
  @Selector([CounterState])
  static getCounter(state: CounterStateModel): number {
    return state.counter;
  }

  @Selector([CounterQuery.getCounter])
  static getCounterSquare(counter: number): number {
    return counter ** 2;
  }
}

 

Two ways to solve the problem:

1. Change the order:

export class CounterQuery {
  @Selector([CounterState])
  static getCounter(state: CounterStateModel): number {
    return state.counter;
  }

  @Selector([CounterQuery.getCounter])
  static getCounterCube(counter: number): number {
    return counter ** 3;
  }

  @Selector([CounterQuery.getCounter])
  static getCounterSquare(counter: number): number {
    return counter ** 2;
  }
}

 

2. Using createSelector:

export class CounterQuery {
  static getCounterCube() {
    return createSelector(
      [CounterQuery.getCounter()],
      (counter: number) => counter ** 3
    );
  }

  static getCounter() {
    return createSelector(
      [CounterState],
      (state: CounterStateModel) => state.counter
    );
  }

  static getCounterSquare() {
    return createSelector(
      [CounterQuery.getCounter()],
      (counter: number) => counter ** 2
    );
  }
}

 

标签:return,NGXS,counter,number,matter,static,getCounter,CounterQuery,orders
来源: https://www.cnblogs.com/Answer1215/p/12202730.html