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. CMMI的SG/GG概念区别与SP/GP概念的区别

    每一个 “流程区域” 会细分为多个子目标.若该子目标只对应单一的流程区域,称为 “特定目标(Specific goal)”:若子目标会涵跨多个流程区域,则称为 “一般目标(Generic goal)” ...

  2. C#,Java,MD5加密对等实现

    1.c#实现 /* *加密生成MD5 */ public static String MD5(string s) { ', 'a', 'b', 'c', 'd', 'e', 'f' }; MD5 md ...

  3. Discuze修改用户名长度限制

    第一步,在网站 uc_client\model 目录下的 user.php文件中,找到如下代码: ? 1 if($len > 15 || $len < 3 || preg_match(&q ...

  4. spring注解、aop(二)

    使用注解配置spring 1.导入 spring-aop-5.0.6.RELEASE.jar包 2.为主配置文件引入新的命名空间 xmlns:context="http://www.spri ...

  5. android悬浮球实现各种功能、快速开发框架、单词、笔记本、应用市场应用等源码

    Android精选源码 悬浮球,实现一键静音,一键锁频,一键截屏等功能 一个Android快速开发框架,MVP架构 Android QQ小红点的实现源码 android一款单词应用完整app源码 an ...

  6. 图像局部显著性—点特征(FREAK)

    参考文章:Freak特征提取算法  圆形区域分割 一.Brisk特征的计算过程(参考对比): 1.建立尺度空间:产生8层Octive层. 2.特征点检测:对这8张图进行FAST9-16角点检测,得到具 ...

  7. openstack--rabbitmq

    一.MQ 全称为 Message Queue, 消息队列( MQ ) 是一种应用程序对应用程序的通信方法.应用程序通过读写出入队列的消息(针对应用程序的数据)来通信,而无需专用连接来链接它们. 消息传 ...

  8. 【剑指Offer】46、圆圈中最后剩下的数

      题目描述:   每年六一儿童节,牛客都会准备一些小礼物去看望孤儿院的小朋友,今年亦是如此.HF作为牛客的资深元老,自然也准备了一些小游戏.其中,有个游戏是这样的:首先,让小朋友们围成一个大圈.然后 ...

  9. 国庆day2

    a[问题描述]你是能看到第一题的 friends呢.—— hja世界上没有什么比卖的这 贵弹丸三还令人绝望事了,所以便么一道题.定义

  10. PY简易爬虫

    然而,实用性很差,仅仅是能用而已. 已知bug: 由于土啬的问题,经常会炸掉.网络不稳定导致各种Connection Aborted/SSLError: EOF occurred in violati ...