Ngxs简单入门
Ngxs简单入门
NGXS is a state management pattern + library for Angular
简单来说就是一个专门应用于angular的状态管理器
简介
ngxs有四个概念:
store
The store is a global state manager that dispatches actions your state containers listen to and provides a way to select data slices out from the global state.
简单说就是一个全局状态管理器,可以执行你的状态容器内的操作(actions),同时可以为外部提供状态的获取方式,例如:执行CountState(状态容器)里的add(),component通过select来订阅状态,而actions以及states的定义都在CountState(状态容器)里。具体可通过下面的例子理解。
actions:
表示在store中注册的动作方法,这个方法用于自行更新组件关注的状态参数信息
select:
表示选定的状态参数,这里用于反馈给外部
state:
States are classes that define a state container.也就是说一个state是一个状态容器
安装
npm install @ngxs/store --save
# or if you are using yarn
yarn add @ngxs/store
然后在app.module.ts中引入NgxsModule
,在创建好state文件后,需要引入state文件,这个文件包含了state以及action:
import { NgModule } from '@angular/core';
import { NgxsModule } from '@ngxs/store';
import { CountState } from './app.state';
@NgModule({
imports: [
NgxsModule.forRoot([CountState ], {
developmentMode: !environment.production
})
]
})
export class AppModule {}
小例子
文件结构
本demo就三个文件,组件与页面进行交互,同时订阅状态,并改变状态;状态容器定义状态states以及actios的处理机制。
代码详解
根模块:app.module.ts
重点:引入NgxsModule 模块以及状态容器CountState(在后面定义)
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { NgxsModule } from '@ngxs/store';
import { AppComponent } from './app.component';
import { CountState } from './app.state';
@NgModule({
imports: [
BrowserModule,
NgxsModule.forRoot([CountState])
],
declarations: [
AppComponent
],
bootstrap: [
AppComponent
]
})
export class AppModule { }
根组件:app.component.ts
重点:引入Store, Select,以及状态容器CountState和Add操作,并订阅关注状态容器CountState里的状态
import { Component } from '@angular/core';
import { Store, Select } from '@ngxs/store';
import { Observable } from 'rxjs';
import { CountState, Add, Reduce, Reset} from './app.state';
@Component({
selector: 'my-app',
template: `
<h1>Count is {{count$ | async}}</h1>
<button (click)="onClick1()">Add 1</button>
<button (click)="onClick2()">Reduce 1</button>
<button (click)="onClick3()">Reset</button>
`
})
export class AppComponent {
@Select(CountState) count$: Observable<number>;
constructor(private store: Store) {}
onClick1() {
this.store.dispatch(new Add());
}
onClick2() {
this.store.dispatch(new Reduce());
}
onClick3() {
this.store.dispatch(new Reset());
}
}
状态容器:app.state.ts
重点:引入State, Action,定义action:Add,Reduce,Reset,定义状态
import { State, Action,StateContext } from '@ngxs/store';
// actions
export class Add {
static readonly type = 'Add';
}
export class Reduce {
static readonly type = 'Reduce';
}
export class Reset {
static readonly type = 'Reset';
}
// states
@State<number>({
name: 'count',
defaults: 0
})
export class CountState {
@Action(Add)
add({ getState, setState }) {
const state = getState();
setState(state + 1);
}
@Action(Reduce)
reduce({ getState, setState }) {
const state = getState();
setState(state - 1);
}
@Action(Reset)
reset(ctx: StateContext<number>) {
ctx.setState(0);
}
}