Action
- 定义方法类
- 默认状态变量
export class FeedZebra {static readonly type = '[Zoo] Feed Zebra';constructor(public name: string, public hayAmount: number) {}}
state
- 不传参数
```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
```typescript// naming your action metadata explicitly makes it easier to understand what the action// is for and makes debugging easier.export class FeedZebra {static readonly type = '[Zoo] FeedZebra';constructor(public zebraToFeed: ZebraFood) {} // new传入的参数}feedZebra(ctx: StateContext<ZooStateModel>, action: FeedZebra) {// 第2个参数,对应constructorconst state = ctx.getState();ctx.setState({...state,zebraFood: [...state.zebraFood,// this is the new ZebraFood instance that we add to the stateaction.zebraToFeed]});}
async
export class ZooState {constructor(private animalService: AnimalService) {}@Action(FeedAnimals)feedAnimals(ctx: StateContext<ZooStateModel>, action: FeedAnimals) {return this.animalService.feed(action.animalsToFeed).pipe(tap(animalsToFeedResult => {const state = ctx.getState();ctx.setState({...state,feedAnimals: [...state.feedAnimals, animalsToFeedResult]});}));}}
Select
相当于get
import { Select } from '@ngxs/store';import { ZooState, ZooStateModel } from './zoo.state';@Component({ ... })export class ZooComponent {// Reads the name of the state from the state class@Select(ZooState) animals$: Observable<string[]>;// Uses the pandas memoized selector to only return pandas@Select(ZooState.pandas) pandas$: Observable<string[]>;// Also accepts a function like our select method@Select(state => state.zoo.animals) animals$: Observable<string[]>;// Reads the name of the state from the parameter@Select() zoo$: Observable<ZooStateModel>;}
组件内
- 通过new修改变量
this.store.dispatch(new AddAnimal(name));
坑
- StateContext的类型写错,导致不能setState


