Angular X中使用ngrx的方法詳解(附源碼)
前言
ngrx 是 Angular框架的狀態(tài)容器,提供可預(yù)測(cè)化的狀態(tài)管理。下面話不多說(shuō),來(lái)一起看看詳細(xì)的介紹:
1.首先創(chuàng)建一個(gè)可路由訪問(wèn)的模塊 這里命名為:DemopetModule。
包括文件:demopet.html、demopet.scss、demopet.component.ts、demopet.routes.ts、demopet.module.ts
代碼如下:
demopet.html
<!--暫時(shí)放一個(gè)標(biāo)簽--> <h1>Demo</h1>
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 {
}
整體代碼結(jié)構(gòu)如下:

運(yùn)行效果如下:只是為了學(xué)習(xí)方便,能夠有個(gè)運(yùn)行的模塊
2.安裝ngrx
npm install @ngrx/core --save npm install @ngrx/store --save npm install @ngrx/effects --save
@ngrx/store是一個(gè)旨在提高寫(xiě)性能的控制狀態(tài)的容器
3.使用ngrx
首先了解下單向數(shù)據(jù)流形式

代碼如下:
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中定義了我們期望狀態(tài)如何發(fā)生改變 Reducer實(shí)現(xiàn)了狀態(tài)具體如何改變
Action與Store之間添加ngrx/Effect 實(shí)現(xiàn)action異步請(qǐng)求與store處理結(jié)果間的解耦
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.調(diào)用ngrx實(shí)現(xiàn)數(shù)據(jù)列表獲取與單個(gè)詳細(xì)信息獲取
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<PetTag>,
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
<h1>Demo</h1>
<pre>
<ul>
<li *ngFor="let d of dataArr | async">
DEMO : {{ d.msg }}
<button (click)="info()">info</button>
</li>
</ul>
{{ dataItem | async | json }}
<h1 *ngFor="let d of dataItem | async"> {{ d.msg }} </h1>
</pre>
6.運(yùn)行效果
初始化時(shí)候獲取數(shù)據(jù)列表

點(diǎn)擊info按鈕 獲取詳細(xì)詳細(xì)
7.以上代碼是從項(xiàng)目中取出的部分代碼,其中涉及到HttpService需要自己封裝,data.json demo.json兩個(gè)測(cè)試用的json文件,名字隨便取的當(dāng)時(shí)。
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.模塊源代碼
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來(lái)一定的幫助,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)腳本之家的支持。
相關(guān)文章
Angular中ng-template和ng-container的應(yīng)用小結(jié)
Angular的日常工作中經(jīng)常會(huì)使用到ng-template和ng-container,本文對(duì)他們做一個(gè)總結(jié),本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2022-06-06
簡(jiǎn)介可以自動(dòng)完成UI的AngularJS工具angular-smarty
這篇文章主要介紹了簡(jiǎn)介可以自動(dòng)完成UI的AngularJS工具angular-smarty,包括其中隔離作用域綁定指令符和promise的使用,需要的朋友可以參考下2015-06-06
AngularJs定時(shí)器$interval 和 $timeout詳解
這篇文章主要介紹了AngularJs定時(shí)器$interval 和 $timeout詳解,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-05-05
AngularJS實(shí)現(xiàn)的select二級(jí)聯(lián)動(dòng)下拉菜單功能示例
這篇文章主要介紹了AngularJS實(shí)現(xiàn)的select二級(jí)聯(lián)動(dòng)下拉菜單功能,結(jié)合完整實(shí)例形式分析了AngularJS實(shí)現(xiàn)二級(jí)聯(lián)動(dòng)菜單的具體操作步驟與相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2017-10-10
AngularJS 最常用的八種功能(基礎(chǔ)知識(shí))
這篇文章主要介紹了AngularJS 最常用的八種功能,非常不錯(cuò),具有參考借鑒價(jià)值,需要的的朋友參考下吧2017-06-06
AngularJS基礎(chǔ) ng-src 指令簡(jiǎn)單示例
本文主要介紹AngularJS ng-src 指令,這里對(duì)ng-src 指令的資料做了詳細(xì)整理,有需要的小伙伴可以參考下2016-08-08
Angular4如何自定義首屏的加載動(dòng)畫(huà)詳解
Angular應(yīng)用程序在首次加載根組件時(shí)會(huì)在瀏覽器的顯示一個(gè)loading...動(dòng)畫(huà),下面這篇文章主要給大家介紹了關(guān)于Angular4如何自定義首屏加載動(dòng)畫(huà)的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面跟著小編來(lái)一起看看吧。2017-07-07
在AngularJS中使用jQuery的zTree插件的方法
這篇文章主要介紹了在AngularJS中使用jQuery的zTree插件的方法,Angular中集成了jqLite,但還不是完全版的jQuery,需要的朋友可以參考下2016-04-04

