[Angular] Introduce to NGXS

Went though tow youtube videos about NGXS

  • https://angularfirebase.com/lessons/ngxs-quick-start-angular-state-management/
  • https://www.youtube.com/watch?v=SfiO3bDUK7Q

The main thing which I am interested about is whether it can achieve the same effect as NGRX.

 

Haven't quite get fianl answer yet, but it looks very promising.

 

1. It is simple.

It has the same partten as redux-like tools.

For example, in the component, you can do:

复制代码
  constructor(private store: Store) {
  }

  addAnimal(name: string) {

    this.store.dispatch(
      // dispatch an action here
    ).subscribe(() => {
      this.name.nativeElement.value = ''; // clean the input field
    });
  }
复制代码

It return an Observable, so you can subscribe it and do anything house keeping stuff here.

 

Action creator:

export class AddAnimal {
  static readonly type = '[Zoo] Add Animals';
  constructor(public payload: string) {}
}

Notice here, it is using static function.

 

But NGXS doesn't have reducer concept, and it doesn't have effect class as well. But I feel this also simply the code a lot. In NGXS, all you need is something called state file:

复制代码
import {Action, Selector, State, StateContext} from '@ngxs/store';
import {AddAnimal, RemoveAnimal} from './animals.action';
import {ZooService} from './zoo.service';

// Define the state Model interface
export interface ZooStateModel {
  animals: string[];
  loading: boolean;
}

// Define the State
@State<ZooStateModel>({
  name: 'zoo',
  defaults: {
    animals: [],
    loading: false
  }
})
export class ZooState {

  // You are able to use DI in state
  constructor(private zooService: ZooService) {
  }

  // Memory selector, for public access the state
  @Selector()
  static getAllAnimals(state: ZooStateModel) {
    return state.animals;
  }

  @Selector()
  static isLoading( state: ZooStateModel){
    return state.loading;
  }

   // Async action
  @Action(AddAnimal)
  addAnimal({getState, setState, patchState, dispatch}: StateContext<ZooStateModel>, {payload}: AddAnimal) {
    const state = getState();
    setState({
      animals: [...state.animals, payload],
      loading: true
    });
    this.zooService.addAnimal(payload)
      .then(() => {
        patchState({
          loading: false
        });
      })
      .catch((res) => {
        const newState = getState();
        setState({
          animals: newState.animals.filter(name => name !== payload),
          loading: false
        });
      });
  }
}
复制代码
  1. You are able to ui Angular DI inside state file. This is a huge advantage.
  2. Actions are no longer sync, it can be async! 
  3. We are still able to use Selector, it works as interal(state) to exteral(component) connect. Notice that Selector are also static method
复制代码
// Inside component you can do:
export class ZooComponent implements OnInit {

  ...

  @Select(ZooState.getAllAnimals) animals$: Observable<any>;
  @Select(ZooState.isLoading) loading$: Observable<boolean>;

  constructor(private store: Store) {
  }

}
复制代码

  4. If you need more than one State working together. it is also easy to achieve, just inject Store to constructor().

复制代码
import {Action, Selector, State} from '@ngxs/store';

interface SelectStateModel {
  id: number;
}

export class SetSelected {
  static readonly type = '[Select] Set Selected';
  constructor(public payload: number) {}
}

@State<SelectStateModel>({
  name: 'selected',
  defaults: {
    id: null
  }
})
export class SelectState {

  @Action(SetSelected)
  setSelected({patchState}, {payload}: SetSelected) {
    patchState({
      id: payload
    });
  }

  @Selector()
  static getSelectedId(state: SelectStateModel) {
    return state.id;
  }
}
复制代码
复制代码
export class ZooState {

  constructor(private zooService: ZooService, private store: Store) {
  }

  @Action(AddAnimal)
  addAnimal(name: string) {
     // to get current selectedId from other state
     const currentId$ = this.store.select(SelectState.getSelectedId);
  }

  ...
}
复制代码

 

posted @   Zhentiw  阅读(953)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2017-04-27 [Angular] Auxiliary named router outlets
2016-04-27 [Angular 2] Using Two Reducers Together
2016-04-27 [Angular 2] Passing Observables into Components with Async Pipe
2016-04-27 [Angular 2] Passing Template Input Values to Reducers
2016-04-27 [Angular 2] Dispatching Action with Payloads and type to Reducers
点击右上角即可分享
微信分享提示