[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
});
});
}
}
- You are able to ui Angular DI inside state file. This is a huge advantage.
- Actions are no longer sync, it can be async!
- 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的更多相关文章
- [Angular 2] Understanding OpaqueToken
When using provider string tokens, there’s a chance they collide with other third-party tokens. Angu ...
- 阿里云 Angular 2 UI框架 NG-ZORRO介绍
说明: Angular2出来后,一直想找个基于Angular2的前端后台管理框架,但一直没有找到比较适合的.前段时间在Angular官网资源无意之间看到NG-ZORRO,NG-ZORRO由阿里计算平台 ...
- ABP 教程文档 1-1 手把手引进门之 AngularJs, ASP.NET MVC, Web API 和 EntityFramework(官方教程翻译版 版本3.2.5)含学习资料
本文是ABP官方文档翻译版,翻译基于 3.2.5 版本 转载请注明出处:http://www.cnblogs.com/yabu007/ 谢谢 官方文档分四部分 一. 教程文档 二.ABP 框架 三. ...
- [转载]前端——实用UI组件库
https://www.cnblogs.com/xuepei/p/7920888.html Angular UI 组件 ngx-bootstrap 是一套Bootstrap 组件 官网:https:/ ...
- 【转】前端——实用UI组件库
Angular UI 组件 ngx-bootstrap 是一套Bootstrap 组件 官网:https://valor-software.com/ngx-bootstrap/#/ github: h ...
- 前端——实用UI组件库
Angular UI 组件 ngx-bootstrap 是一套Bootstrap 组件 官网:https://valor-software.com/ngx-bootstrap/#/ github: h ...
- [Angular 2] More on *ngFor, @ContentChildren & QueryList<>
In previous artical, we introduce the how to use *ngFor. The limitation for previous solution to dis ...
- [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 ...
- [Angular 2] Component relative paths
Oingial aritial --> Link Take away: import { Component, OnInit } from '@angular/core'; @Component ...
随机推荐
- 初识Java,Java语言概述
Java语言是SUN(斯坦福大学网络公司)公司1995年推出的一门高级编程语言,由此James Gosling被公认为Java语言之父.Java语言起初运用在小型的家用电子产品上,后来随着互联网的发展 ...
- UIDynamicBehavior的简单使用:接球小游戏
一.概念扩充: 1.在开发中,我们可以使用UIKit中提供的仿真行为,实现与现实生活中类似的物理仿真动画,UIKit动力学最大的特点是将现实世界动力驱动的动画引入了UIKit,比如重力,铰链连接,碰撞 ...
- (Go)09.指针赋值修改示例
答案: 1 package main 2 import ( 3 "fmt" 4 ) 5 6 7 func modify(p *int) { 8 fmt.Println(p) 9 ...
- Django day06 模版层(一) 变量和深度查询
一.模版语法之变量: 1 - {{ 变量 }} ******重要*******{#这个相当于print了该变量#} def index(request): name = 'prince' #字符串 ...
- flash 遮住 div 解决办法
被遮盖的div 下面的代码 <!--列表菜单--> <div id="opreationmenu" style="posit ...
- 2019手机号码JS正则表达式
前端的正则表达式验证往往是最繁多最复杂的,所以整理了一些最近自己常用的正则表达式,希望能对大家有所帮助! /* 合法uri */ export function validateURL(textval ...
- gdb打印vector
1.gdb版本大于7.0 (gdb) p yourVector 2.打印整个vector (gdb) p *(yourVector._M_impl._M_start)@yourVector.size( ...
- B - Taxi(贪心)
Problem description After the lessons n groups of schoolchildren went outside and decided to visit P ...
- C#之单列双列集合绑定数据
---恢复内容开始--- 1.单列集合绑定方式 davList.DataSource=new BindingList<类型名>(集合名); 2.双列集合绑定方式 BindingSource ...
- Spring Cloud (2) 服务消费者-基础
LoadBalancerClient 使用Spring Cloud提供的负载均衡器客户端来实现服务的消费. 首先创建一个服务消费者工程,命名为com.david.consumer,并在pom.xml中 ...