ngrx
的认识ngrx
是借鉴redux
的思惟,专门为angular
中定制的一个状态管理的包,相似react
中的redux
、vue
中的vuex
,主要包括如下几个模块(本文先介绍@ngrx/store
)
@ngrx/store
@ngrx/store-devtools
@ngrx/effects
@ngrx/router-store
@ngrx/entity
@ngrx/data
@ngrx/schematics
ngrx
的场景
angular
项目开发中属于非必须的一、使用@angular/cli
初始化项目vue
ng new angular-ngrx
复制代码
二、建立一个数据的module
(手动修更名字为AppStoreModule
,否则会和@ngrx/store
中的重名)react
ng g m store
复制代码
三、在store
文件夹下建立三个文件夹git
actions
reducers
selectors
(非必须的,仅仅是对于一个状态树是对象的时候,写一个方法选择状态树中的一个节点)四、手动安装@ngrx/store
github
npm install @ngrx/store --save
复制代码
五、手动安装@ngrx/store-devtools
vuex
npm install @ngrx/store-devtools --save
复制代码
六、在reducers
文件夹下建立index.ts
(使用ng add @ngrx/store
会默认生成的)shell
import {
ActionReducerMap,
MetaReducer
} from '@ngrx/store';
import { environment } from '../../../environments/environment';
// 项目中所有的状态
export interface State {}
// 所有的reducer函数
export const reducers: ActionReducerMap<State> = {};
export const metaReducers: MetaReducer<State>[] = !environment.production ? [] : [];
复制代码
七、浏览器要安装redux
插件npm
八、在store.module.ts
中配置浏览器调试的更多配置见redux
@NgModule({
declarations: [],
imports: [
StoreModule.forRoot(reducers, {
metaReducers,
runtimeChecks: {
strictStateImmutability: true,
strictActionImmutability: true,
strictStateSerializability: true,
strictActionSerializability: true,
}
}),
StoreDevtoolsModule.instrument({
maxAge: 20,
logOnly: environment.production
})
]
})
export class AppStoreModule { }
复制代码
@ngrx/store
book
组件