Ngxs简介
ngxs是angular的一个状态管理框架,可以全局的管理应用程序的所有状态。
使用的场景:
- 当应用程序的各个组件需要共享某些数据时
- 当需要组件变得更加独立,更易于测试
- 当程序的状态改变来自各个页面的组件时
- 当多人共同协作一个大型项目时
ngxs有四个概念:
- state:表示需要关注的状态参数信息
- action:表示在store中注册的动作方法,这个方法用于自行更新组件关注的状态参数信息
- select:表示选定的状态参数,这里用于反馈给外部
- store:用于存储select、action和state
Ngxs实例
接下来会通过一个实例来详解上述各类概念
1.编写app.state.ts(store核心包括action、state等)
import { State, Action, StateContext, Selector } from '@ngxs/store';
export class Add {
static readonly type = 'Add';
}
export class Reduce {
static readonly type = 'Reduce';
}
export class Reset {
static readonly type = 'Reset';
}
@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);
}
}
如上所示,State为我们需要关注并且管理的状态(State),下面定义其默认值为0,对于这个状态我们定义了几种方法(Action)来描述状态的变化
2.编写component和html
这里使用到Select来接收这个状态,并且将其定义为一个Observable,这里与异步Rxjs相关。
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: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
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());
}
}
<h1>Count is {{count$ | async}}</h1>
<button (click)="onClick1()">Add 1</button>
<button (click)="onClick2()">Reduce 1</button>
<button (click)="onClick3()">Reset</button>
3.在app.module.ts中引入nsxsmodule并且创建根路由
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NgxsModule } from '@ngxs/store';
import { CountState } from './app.state';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
NgxsModule.forRoot([CountState])
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
如上一个简单的ngxs状态管理实例便实现了