Angular狀態管理的使用

CRown團隊發表於2017-12-25

ngrx 是 Angular框架的狀態容器,提供可預測化的狀態管理。

1.首先建立一個可路由訪問的模組 這裡命名為:DemopetModule。

包括檔案:demopet.html、demopet.scss、demopet.component.ts、demopet.routes.ts、demopet.module.ts

程式碼如下:
複製程式碼

 demopet.html

Demo

 demopet.scss

h1{ color:#d70029; } demopet.component.ts

import { Component} from '@angular/core';

@Component({ selector: 'demo-pet', styleUrls: ['./demopet.scss'], templateUrl: './demopet.html' }) export class DemoPetComponent { //nothing now... } demopet.routes.ts

import { DemoPetComponent } from './demopet.component';

export const routes = [ { path: '', pathMatch: 'full', children: [ { path: '', component: DemoPetComponent } ] } ]; demopet.module.ts

import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { routes } from './demopet.routes';

@NgModule({ declarations: [ DemoPetComponent, ], imports: [ CommonModule, FormsModule, RouterModule.forChild(routes) ], providers: [ ] }) export class DemoPetModule {

} 整體程式碼結構如下:

Angular狀態管理的使用

執行效果如下:只是為了學習方便,能夠有個執行的模組

Angular狀態管理的使用

2.安裝ngrx

npm install @ngrx/core --save

npm install @ngrx/store --save

npm install @ngrx/effects --save

@ngrx/store是一個旨在提高寫效能的控制狀態的容器

3.使用ngrx

首先了解下單向資料流形式

Angular狀態管理的使用

程式碼如下:

pet-tag.actions.ts

import { Injectable } from '@angular/core'; import { Action } from '@ngrx/store';

@Injectable() export class PettagActions{ static LOAD_DATA='Load Data'; loadData():Action{ return { type:PettagActions.LOAD_DATA }; }

static LOAD_DATA_SUCCESS='Load Data Success';
loadDtaSuccess(data):Action{
    return {
        type:PettagActions.LOAD_DATA_SUCCESS,
        payload:data
    };
}


static LOAD_INFO='Load Info';
loadInfo():Action{
    return {
        type:PettagActions.LOAD_INFO
    };
}

static LOAD_INFO_SUCCESS='Load Info Success';
loadInfoSuccess(data):Action{
    return {
        type:PettagActions.LOAD_INFO_SUCCESS,
        payload:data
    };
}
複製程式碼

} pet-tag.reducer.ts

import { Action } from '@ngrx/store'; import { Observable } from 'rxjs/Observable'; import { PettagActions } from '../action/pet-tag.actions';

export function petTagReducer(state:any,action:Action){ switch(action.type){

    case PettagActions.LOAD_DATA_SUCCESS:{

        return action.payload;
    }

    // case PettagActions.LOAD_INFO_SUCCESS:{

    //     return action.payload;
    // }

    default:{

        return state;
    }
}
複製程式碼

}

export function infoReducer(state:any,action:Action){ switch(action.type){

    case PettagActions.LOAD_INFO_SUCCESS:{

        return action.payload;
    }

    default:{

        return state;
    }
}
複製程式碼

} NOTE:Action中定義了我們期望狀態如何發生改變 Reducer實現了狀態具體如何改變

Action與Store之間新增ngrx/Effect 實現action非同步請求與store處理結果間的解耦

pet-tag.effect.ts

import { Injectable } from '@angular/core'; import { Effect,Actions } from '@ngrx/effects'; import { PettagActions } from '../action/pet-tag.actions'; import { PettagService } from '../service/pet-tag.service';

@Injectable() export class PettagEffect {

constructor(
    private action$:Actions,
    private pettagAction:PettagActions,
    private service:PettagService
){}


@Effect() loadData=this.action$
            .ofType(PettagActions.LOAD_DATA)
            .switchMap(()=>this.service.getData())
            .map(data=>this.pettagAction.loadDtaSuccess(data))


@Effect() loadInfo=this.action$
            .ofType(PettagActions.LOAD_INFO)
            .switchMap(()=>this.service.getInfo())
            .map(data=>this.pettagAction.loadInfoSuccess(data));
複製程式碼

}

4.修改demopet.module.ts 新增 ngrx支援

import { StoreModule } from '@ngrx/store'; import { EffectsModule } from '@ngrx/effects'; import { PettagActions } from './action/pet-tag.actions'; import { petTagReducer,infoReducer } from './reducer/pet-tag.reducer'; import { PettagEffect } from './effect/pet-tag.effect'; @NgModule({ declarations: [ DemoPetComponent, ], imports: [ CommonModule, FormsModule, RouterModule.forChild(routes), //here new added StoreModule.provideStore({ pet:petTagReducer, info:infoReducer }), EffectsModule.run(PettagEffect) ], providers: [ PettagActions, PettagService ] }) export class DemoPetModule { }

5.呼叫ngrx實現資料列表獲取與單個詳細資訊獲取

demopet.component.ts

import { Component, OnInit, ViewChild, AfterViewInit } from '@angular/core'; import { Observable } from "rxjs"; import { Store } from '@ngrx/store'; import { Subscription } from 'rxjs/Subscription'; import { HttpService } from '../shared/services/http/http.service'; import { PetTag } from './model/pet-tag.model'; import { PettagActions } from './action/pet-tag.actions';

@Component({ selector: 'demo-pet', styleUrls: ['./demopet.scss'], templateUrl: './demopet.html' }) export class DemoPetComponent {

private sub: Subscription; public dataArr: any; public dataItem: any; public language: string = 'en'; public param = {value: 'world'};

constructor( private store: Store, private action: PettagActions ) {

this.dataArr = store.select('pet');
複製程式碼

}

ngOnInit() {

this.store.dispatch(this.action.loadData());
複製程式碼

}

ngOnDestroy() {

this.sub.unsubscribe();
複製程式碼

}

info() {

console.log('info');
this.dataItem = this.store.select('info');
this.store.dispatch(this.action.loadInfo());
複製程式碼

}

} demopet.html

Demo

   
  • DEMO : {{ d.msg }}
{{ dataItem | async | json }}

{{ d.msg }}

6.執行效果

初始化時候獲取資料列表

Angular狀態管理的使用

點選info按鈕 獲取詳細詳細

Angular狀態管理的使用

7.以上程式碼是從專案中取出的部分程式碼,其中涉及到HttpService需要自己封裝,data.json demo.json兩個測試用的json檔案,名字隨便取的當時。

http.service.ts

import { Inject, Injectable } from '@angular/core'; import { Http, Response, Headers, RequestOptions, URLSearchParams } from '@angular/http'; import { Observable } from "rxjs"; import 'rxjs/add/operator/map'; import 'rxjs/operator/delay'; import 'rxjs/operator/mergeMap'; import 'rxjs/operator/switchMap'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; import { handleError } from './handleError'; import { rootPath } from './http.config';

@Injectable() export class HttpService {

private _root: string="";

constructor(private http: Http) {

    this._root=rootPath;
}

public get(url: string, data: Map<string, any>, root: string = this._root): Observable<any> {
    if (root == null) root = this._root;
    
    let params = new URLSearchParams();
    if (!!data) {
        data.forEach(function (v, k) {
            params.set(k, v);
        });
   
    }
    return this.http.get(root + url, { search: params })
                    .map((resp: Response) => resp.json())
                    .catch(handleError);
}
複製程式碼

}

8.微信公眾號

Angular狀態管理的使用

相關文章