angular8与ngrx8的结合使用

1、案例运行后的效果图

2、关于ngrx的认识

  • 一、官网地址
  • 二、ngrx是借鉴redux的思惟,专门为angular中定制的一个状态管理的包,相似react中的reduxvue中的vuex,主要包括如下几个模块(本文先介绍@ngrx/store)
    • @ngrx/store
    • @ngrx/store-devtools
    • @ngrx/effects
    • @ngrx/router-store
    • @ngrx/entity
    • @ngrx/data
    • @ngrx/schematics
  • 三、须要使用ngrx的场景
    • angular项目开发中属于非必须的
    • 大项目中须要进行组件通信,数据共享

3、构建项目

  • 一、使用@angular/cli初始化项目vue

    ng new angular-ngrx
    复制代码
  • 二、建立一个数据的module(手动修更名字为AppStoreModule,否则会和@ngrx/store中的重名)react

    ng g m store
    复制代码
  • 三、在store文件夹下建立三个文件夹git

    • actions
    • reducers
    • selectors(非必须的,仅仅是对于一个状态树是对象的时候,写一个方法选择状态树中的一个节点)
  • 四、手动安装@ngrx/storegithub

    npm install @ngrx/store --save
    复制代码
  • 五、手动安装@ngrx/store-devtoolsvuex

    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 { }
    复制代码

4、在项目中使用@ngrx/store

  • 一、代码的使用见github中的book组件
相关文章
相关标签/搜索