angular8與ngrx8的基本使用步驟

一、案例運行後的效果圖

在這裏插入圖片描述

二、關於ngrx的認識

  • 1、官網地址
  • 2、ngrx是借鑑redux的思維,專門爲angular中定製的一個狀態管理的包,類似react中的reduxvue中的vuex,主要包括以下幾個模塊(本文先介紹@ngrx/store)
    • @ngrx/store
    • @ngrx/store-devtools
    • @ngrx/effects
    • @ngrx/router-store
    • @ngrx/entity
    • @ngrx/data
    • @ngrx/schematics
  • 3、需要使用ngrx的場景
    • angular項目開發中屬於非必須的
    • 大項目中需要進行組件通訊,數據共享

三、構建項目

  • 1、使用@angular/cli初始化項目

    ng new angular-ngrx
    
  • 2、創建一個數據的module(手動修改名字爲AppStoreModule,不然會和@ngrx/store中的重名)

    ng g m store
    
  • 3、在store文件夾下創建三個文件夾

    • actions
    • reducers
    • selectors(非必須的,僅僅是對於一個狀態樹是對象的時候,寫一個方法選擇狀態樹中的一個節點)
  • 4、手動安裝@ngrx/store

    npm install @ngrx/store --save
    
  • 5、手動安裝@ngrx/store-devtools

    npm install @ngrx/store-devtools --save
    
  • 6、在reducers文件夾下創建index.ts(使用ng add @ngrx/store會默認生成的)

    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 ? [] : [];
    
  • 7、瀏覽器要安裝redux插件

  • 8、在store.module.ts中配置瀏覽器調試的更多配置見

    @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

  • 1、代碼的使用見github中的book組件
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章