一、案例運行後的效果圖
二、關於ngrx
的認識
- 1、官網地址
- 2、
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
- 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
組件