Action

  1. 定义方法类
  2. 默认状态变量
  1. export class FeedZebra {
  2. static readonly type = '[Zoo] Feed Zebra';
  3. constructor(public name: string, public hayAmount: number) {}
  4. }

state

  1. 不传参数 ```typescript export class ZooState { @Action(FeedAnimals) feedAnimals(ctx: StateContext) { const state = ctx.getState(); ctx.setState({ …state, feed: !state.feed // 不是入参改变 }); } }

this.store.dispatch(new ZooState()); // 没传参数,即feedAnimals的第二个arguments

  1. ```typescript
  2. // naming your action metadata explicitly makes it easier to understand what the action
  3. // is for and makes debugging easier.
  4. export class FeedZebra {
  5. static readonly type = '[Zoo] FeedZebra';
  6. constructor(public zebraToFeed: ZebraFood) {} // new传入的参数
  7. }
  8. feedZebra(ctx: StateContext<ZooStateModel>, action: FeedZebra) {// 第2个参数,对应constructor
  9. const state = ctx.getState();
  10. ctx.setState({
  11. ...state,
  12. zebraFood: [
  13. ...state.zebraFood,
  14. // this is the new ZebraFood instance that we add to the state
  15. action.zebraToFeed
  16. ]
  17. });
  18. }

async

  1. export class ZooState {
  2. constructor(private animalService: AnimalService) {}
  3. @Action(FeedAnimals)
  4. feedAnimals(ctx: StateContext<ZooStateModel>, action: FeedAnimals) {
  5. return this.animalService.feed(action.animalsToFeed).pipe(
  6. tap(animalsToFeedResult => {
  7. const state = ctx.getState();
  8. ctx.setState({
  9. ...state,
  10. feedAnimals: [...state.feedAnimals, animalsToFeedResult]
  11. });
  12. })
  13. );
  14. }
  15. }

Select

相当于get

  1. import { Select } from '@ngxs/store';
  2. import { ZooState, ZooStateModel } from './zoo.state';
  3. @Component({ ... })
  4. export class ZooComponent {
  5. // Reads the name of the state from the state class
  6. @Select(ZooState) animals$: Observable<string[]>;
  7. // Uses the pandas memoized selector to only return pandas
  8. @Select(ZooState.pandas) pandas$: Observable<string[]>;
  9. // Also accepts a function like our select method
  10. @Select(state => state.zoo.animals) animals$: Observable<string[]>;
  11. // Reads the name of the state from the parameter
  12. @Select() zoo$: Observable<ZooStateModel>;
  13. }

组件内

  1. 通过new修改变量
    1. this.store.dispatch(new AddAnimal(name));

  1. StateContext的类型写错,导致不能setState

image.png

image.png