站長資訊網(wǎng)
        最全最豐富的資訊網(wǎng)站

        Angular使用ngrx/store做狀態(tài)管理

        本篇文章給大家介紹一下Angular ngrx/store狀態(tài)管理的使用。有一定的參考價值,有需要的朋友可以參考一下,希望對大家有所幫助。

        相關(guān)教程推薦:《angular教程》

        Angular中使用ngrx做狀態(tài)管理

        簡介

        ngrx/store的靈感來源于Redux,是一款集成RxJS的Angular狀態(tài)管理庫,由Angular的布道者Rob Wormald開發(fā)。它和Redux的核心思想相同,但使用RxJS實現(xiàn)觀察者模式。它遵循Redux核心原則,但專門為Angular而設(shè)計。

        Angular中的狀態(tài)管理大部分可以被service接管,那么在一些中大型的項目中,這樣做的弊端就會顯露出來,其中之一就是狀態(tài)流混亂,不利于后期維護(hù),后來便借鑒了redux的狀態(tài)管理模式并配上rxjs流式編程的特點(diǎn)形成了@ngrx/store這么一個作用于Angular的狀態(tài)管理工具.

        • StoreModule:
          StoreModule是@ngrx/store API中的一個模塊,它被用來在應(yīng)用模塊中配置reducer。

        • Action:
          Action是狀態(tài)的改變。它描述了某個事件的發(fā)生,但是沒有指定應(yīng)用的狀態(tài)如何改變。

        • Store:
          它提供了Store.select()和Store.dispatch()來與reducer協(xié)同工作。Store.select()用于選擇一個selector,
          Store.dispatch(
          {
          type:‘a(chǎn)dd’,
          payload:{name:‘111’}
          }
          )
          用于向reducer分發(fā)action的類型。

        @NgRx/Store 狀態(tài)管理的三個原則

        首先,@NgRx/Store 同樣遵守 Redux 的三個基本原則:

        • 單一數(shù)據(jù)源

        這個原則是整個單頁應(yīng)用的狀態(tài)通過object tree(對象樹)的形式存儲在store 里面。
        這個定義十分抽象其實就是把所有需要共享的數(shù)據(jù)通過javascript 對象的形式存儲下來

        state = {     application:'angular app',     shoppingList:['apple', 'pear'] }
        • state is read-only(狀態(tài)只能是只讀形式)

        這個 ngrx/store 核心之一就是用戶不能直接修改狀態(tài)內(nèi)容。 舉個例子,如果我們需要保存了登錄頁面狀態(tài),狀態(tài)信息需要記錄登錄用戶的名字。 當(dāng)?shù)卿浢指淖?,我們不能直接修改狀態(tài)保存的用戶名字

        state={'username':'kat'}, //用戶重新登錄別的賬戶為tom state.username = 'tom'  //在ngrx store 這個行為是絕對不允許的
        • changes are made with pure functions(只能通過調(diào)用函數(shù)來改變狀態(tài))

        由于不能直接需改狀態(tài),ngrx/store 同時引入了一個叫做reducer(聚合器)的概念。通過reducer 來修改狀態(tài)。

        function reducer(state = 'SHOW_ALL', action) {     switch (action.type) {       	case 'SET_VISIBILITY_FILTER':         	return Object.assign({}, state  ,newObj);           default:         	return state           } 	}

        ngrx/store使用實例

        1.安裝@ngrx/store

        yarn add @ngrx/store

        2. 創(chuàng)建 state, action, reducer

        state 狀態(tài):
        appstorestate.ts

        //下面是使用接口的情況, 更規(guī)范 export interface TaskList {   id: number;   text: string;   complete: boolean; }  export const TASKSAll: TaskList[] = [   {id: 1, text: 'Java Article 1', complete: false},   {id: 2, text: 'Java Article 2', complete: false} ]  export interface AppState {   count: number;   todos: TaskList;   // 如果要管理多個狀態(tài),在這個接口中添加即可 }  //這個是不用接口的情況 // export interface AppState { //     count: number; //     todos: any; //     // 如果要管理多個狀態(tài),在這個接口中添加即可 //   }

        reducer
        appstorereducer.ts

        // reducer.ts,一般需要將state,action,reducer進(jìn)行文件拆分 import { Action } from '@ngrx/store';  export const INCREMENT = 'INCREMENT'; export const DECREMENT = 'DECREMENT'; export const RESET = 'RESET';  const initialState = 0; // reducer定義了action被派發(fā)時state的具體改變方式 export function counterReducer(state: number = initialState, action: Action) {   switch (action.type) {     case INCREMENT:       return state + 1;      case DECREMENT:       return state - 1;      case RESET:       return 0;      default:       return state;   } }

        actions

        如果需要把a(bǔ)ction 單獨(dú)提取出來, 參考 后面的
        5 如果想把a(bǔ)ction分離出來如何處理?

        3. 注冊store

        根模塊:
        app/app.module.ts

        import { NgModule } from '@angular/core'; import { StoreModule } from '@ngrx/store'; // StoreModule: StoreModule是@ngrx/storeAPI中的一個模塊, // 它被用來在應(yīng)用模塊中配置reducer。  import {counterReducer} from './store/reducer';  @NgModule({   imports: [   	StoreModule.forRoot({ count: counterReducer }), // 注冊store   ], }) export class AppModule {}

        4. 使用store

        在組件或服務(wù)中注入store進(jìn)行使用

        以 appmodulearticlearticle.component.ts 組件為例:

        // 組件級別 import { Component } from '@angular/core'; import { Store, select } from '@ngrx/store'; import { Observable } from 'rxjs'; import { INCREMENT, DECREMENT, RESET} from '../../store/reducer';  interface AppState {   count: number; }  @Component({   selector: 'app-article',   templateUrl: './article.component.html',   styleUrls: ['./article.component.css'] }) export class ArticleComponent  {   count: Observable<number>;    constructor(private store: Store<AppState>) { // 注入store     this.count = store.pipe(select('count'));      // 從app.module.ts中獲取count狀態(tài)流   }    increment() {     this.store.dispatch({ type: INCREMENT });   }    decrement() {     this.store.dispatch({ type: DECREMENT });   }    reset() {     this.store.dispatch({ type: RESET });   } }

        模板頁面:
        appmodulearticlearticle.component.html

        <div class="state-count">      <button (click)="increment()">增加Increment</button>     <div>Current Count: {{ count | async }}</div>     <button (click)="decrement()">減少Decrement</button>      <button (click)="reset()">Reset Counter</button> </div>

        這里使用了 管道符 async, 在子模塊里直接使用快報錯 , 如果在子模塊要實現(xiàn) 數(shù)據(jù)的雙向綁定也會報錯,具體原因參照 課件說明的 問題: The pipe ‘a(chǎn)sync’ could not be found?

        如何做到在模板頁面中不使用管道 來渲染頁面 ?

        修改如下:

        count: Observable<number>;  constructor(private store: Store<AppState>) { // 注入store     var stream = store.pipe(select('count'));      // 從app.module.ts中獲取count狀態(tài)流     stream.subscribe((res)=>{           this.count = res;       })   }

        為了管理方便, 一般會把 type , state, actions,reducers 分開來管理

        5 如果想把a(bǔ)ction分離出來如何處理?

        1. 新建 appstoreactions.ts 文件
        import { Injectable } from '@angular/core'; import { INCREMENT, DECREMENT, RESET } from './types';  @Injectable() export class CounterAction{     // Add=function(){}     Add(){         return { type: INCREMENT }     } }  // 就只這樣導(dǎo)出是不行的 // export function Add1(){ //     return { type: INCREMENT } // }
        1. 在根模塊 app.module.ts 注冊
        import {CounterAction} from './store/actions';  ...   providers: [CounterAction],
        1. 在組件中使用 – article.component.ts
        import {CounterAction} from '../../store/actions';  export class ArticleComponent implements OnInit {    constructor(     private action: CounterAction  //注入CounterAction     ) { }      increment() {     // this.store.dispatch({ type: INCREMENT });      //把 actions分離出去     this.store.dispatch(this.action.Add());         } }

        贊(0)
        分享到: 更多 (0)
        網(wǎng)站地圖   滬ICP備18035694號-2    滬公網(wǎng)安備31011702889846號
        主站蜘蛛池模板: 最新国产精品无码| 久久亚洲私人国产精品vA| 中文精品99久久国产 | 久久精品国产清高在天天线| 国产精品亚洲精品日韩已方| 国产精品水嫩水嫩| 日韩一区二区精品观看| 国产成人精品久久综合| 国产精品欧美日韩| 国产日韩精品中文字无码| 呦交小u女国产精品视频| 精品一区二区三区免费观看| 尤物国产在线精品福利一区| 国产精品无码a∨精品| 夜夜高潮夜夜爽国产伦精品| 精品第一国产综合精品蜜芽| 国产99精品一区二区三区免费| laowang在线精品视频| 久久精品毛片免费观看| 亚洲国产一成人久久精品| 久久久久国产精品嫩草影院| 国产成人精品亚洲精品| 91亚洲国产成人久久精品网址| 久久精品国产亚洲麻豆| 国产精品爽爽va在线观看网站| 精品国产福利在线观看| 久久亚洲精品成人av无码网站| 亚洲国产另类久久久精品黑人| 亚洲性日韩精品国产一区二区 | 国产成人精品视频一区二区不卡| 亚洲精品无码专区在线在线播放 | 久久精品无码一区二区app| 国产乱子伦精品无码专区| 91久久精品国产免费直播| 丝袜美腿国产精品视频一区| 久久国产精品久久精品国产| 国产精品99久久精品| 精品999在线| 亚洲国产综合精品中文第一区| 欧美精品亚洲精品日韩专区va| 日韩精品在线看|