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

[Angular] Introduce to NGXS的更多相关文章

  1. [Angular 2] Understanding OpaqueToken

    When using provider string tokens, there’s a chance they collide with other third-party tokens. Angu ...

  2. 阿里云 Angular 2 UI框架 NG-ZORRO介绍

    说明: Angular2出来后,一直想找个基于Angular2的前端后台管理框架,但一直没有找到比较适合的.前段时间在Angular官网资源无意之间看到NG-ZORRO,NG-ZORRO由阿里计算平台 ...

  3. ABP 教程文档 1-1 手把手引进门之 AngularJs, ASP.NET MVC, Web API 和 EntityFramework(官方教程翻译版 版本3.2.5)含学习资料

    本文是ABP官方文档翻译版,翻译基于 3.2.5 版本 转载请注明出处:http://www.cnblogs.com/yabu007/  谢谢 官方文档分四部分 一. 教程文档 二.ABP 框架 三. ...

  4. [转载]前端——实用UI组件库

    https://www.cnblogs.com/xuepei/p/7920888.html Angular UI 组件 ngx-bootstrap 是一套Bootstrap 组件 官网:https:/ ...

  5. 【转】前端——实用UI组件库

    Angular UI 组件 ngx-bootstrap 是一套Bootstrap 组件 官网:https://valor-software.com/ngx-bootstrap/#/ github: h ...

  6. 前端——实用UI组件库

    Angular UI 组件 ngx-bootstrap 是一套Bootstrap 组件 官网:https://valor-software.com/ngx-bootstrap/#/ github: h ...

  7. [Angular 2] More on *ngFor, @ContentChildren & QueryList<>

    In previous artical, we introduce the how to use *ngFor. The limitation for previous solution to dis ...

  8. [AngularJS - thoughtram] Exploring Angular 1.3: Binding to Directive Controllers

    The post we have: http://www.cnblogs.com/Answer1215/p/4185504.html gives a breif introduce about bin ...

  9. [Angular 2] Component relative paths

    Oingial aritial --> Link Take away: import { Component, OnInit } from '@angular/core'; @Component ...

随机推荐

  1. 协同过滤算法中皮尔逊相关系数的计算 C++

    template <class T1, class T2>double Pearson(std::vector<T1> &inst1, std::vector<T ...

  2. 3-5 第三天 Koa 和 Express 中间件

    Koa和Express这两个框架除了在接收请求和返回数据方面有非常通用.好用的封装以外,最有价值的地方就是它们有自己的中间件机制,所以说中间件可以看做是流水线上一个又一个的加工房间,每个加工的房间都只 ...

  3. git 设定全局ignore

    创建: 2017/08/08   位置: $HOME/.config/git/ignore git/ignore 要自建 内容  https://github.com/github/gitignore ...

  4. .NET Core Run On Docker By Kubernetes 系列文章汇总

    前言介绍 .NET Core是微软新一代主力编程平台,开源.免费.跨平台.轻量级.高性能,支持Linux.Docker.k8s等环境,适合开发微服务.云原生.大型互联网应用.全开源解决方案. Dock ...

  5. Asp.net三种事务处理

    事务处理是在数据处理时经常遇到的问题,经常用到的方法有以下三种总结整理如下:方法1:直接写入到sql 中在存储过程中使用 BEGIN TRANS, COMMIT TRANS, ROLLBACK TRA ...

  6. 表单校验插件(bootstrap-validator)

    表单校验插件(bootstrap-validator) 参考文档 http://blog.csdn.net/nazhidao/article/details/51542508 http://blog. ...

  7. OpenVX

    OpenVX openvx  1. 编译 尝试编译openvx_sample,下载相关代码. 下载的sample code直接使用make可以生成libopenvx.so. 使用python Buil ...

  8. 设置Hadoop的 dataNode的单个Map的内存配置

    1.进入hadoop的配置目录 ,找到 环境变量的 $HADOOP_HOME cd $HADOOP_HOME 2.修改dataNode 节点的 单个map的能使用的内存配置 找到配置的文件: /opt ...

  9. js document 触发按键事件

    // 键盘控制 var keyEvent = (function () { document.onkeydown = function (e) { if (e.keyCode === 38) { // ...

  10. 修改默认的gitlab clone地址,要不每次都得自己修改

        这个是无法clone的,得换成gitlab的ip地址 下面进行修改     sudo vim /opt/gitlab/embedded/service/gitlab-rails/config/ ...