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. 0503 php中for与foreach的区别

    结论: foreach:只能用于数组和对象,如果是非索引数组,只可以用foreach. for:如果是索引数组,可以用for遍历. foreach循环结构是按照数组内部的指针去循环的,当 foreac ...

  2. bzoj1593 [Usaco2008 Feb]Hotel 旅馆(线段树)

    1593: [Usaco2008 Feb]Hotel 旅馆 Time Limit: 10 Sec  Memory Limit: 64 MBSubmit: 758  Solved: 419[Submit ...

  3. SfMLearner论文笔记——Unsupervised Learning of Depth and Ego-Motion from Video

    1. Abstract 提出了一种无监督单目深度估计和相机运动估计的框架 利用视觉合成作为监督信息,使用端到端的方式学习 网络分为两部分(严格意义上是三个) 单目深度估计 多视图姿态估计 解释性网络( ...

  4. BZOJ 1914 计算几何

    思路: 我们可以算不合法的 如果三个点都在同一侧 就不合法.. 用总方案数减掉就可以了 (有神奇的实现方法...) //By SiriusRen #include <cmath> #inc ...

  5. Combotree--别样的构建层级json字符串

    1.先看效果 2.需要使用层级json格式,如: 3.先不要着急怎么去实现它,先来想想怎么用对象来描述它 4.代码 protected void Page_Load(object sender, Ev ...

  6. Bootstrap栅格系统&媒体查询

    bootstrap中几乎所有元素的盒子模型为IE下的盒模型,通俗点说就是box-sizing设置成了:border-box.   栅格系统 媒体查询 媒体查询是非常别致的"有条件的 CSS ...

  7. mysql数据库知识点总结

    一.数据库的基本操作 --------------------------------------------------------------数据库的安装以后更新----------------- ...

  8. springBoot jar/war打包部署问题

    先给pom.xml配置导出插件 <!--配置插件将Maven 插件 导出成为jar --> <plugin> <groupId>org.springframewor ...

  9. phpmyadmin搭建

    phpadmin配置: 一.phpadmin安装及配置 1.解压phpadmin压缩包,并复制到 /usr/local/apache2/htdocs目录,重命名为dataManage 2.进入data ...

  10. 【sqli-labs】 less27a GET- Blind based -All you Union&Select Belong to us -Double Quotes(GET型基于盲注的去除了Union和Select的双引号注入)

    和less 27一样,单引号换双引号 http://192.168.136.128/sqli-labs-master/Less-27a/?id=0"%a0uNion%a0sElect%a01 ...