Angular X中使用ngrx的方法详解(附源码)


Posted in Javascript onJuly 10, 2017

前言

ngrx 是 Angular框架的状态容器,提供可预测化的状态管理。下面话不多说,来一起看看详细的介绍:

1.首先创建一个可路由访问的模块 这里命名为:DemopetModule。

包括文件:demopet.html、demopet.scss、demopet.component.ts、demopet.routes.ts、demopet.module.ts

代码如下:

demopet.html

<!--暂时放一个标签-->
<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 {


}

整体代码结构如下:

Angular X中使用ngrx的方法详解(附源码)

运行效果如下:只是为了学习方便,能够有个运行的模块

Angular X中使用ngrx的方法详解(附源码) 

2.安装ngrx

npm install @ngrx/core --save

npm install @ngrx/store --save

npm install @ngrx/effects --save

@ngrx/store是一个旨在提高写性能的控制状态的容器

3.使用ngrx

首先了解下单向数据流形式

Angular X中使用ngrx的方法详解(附源码)

代码如下:

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<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.运行效果

初始化时候获取数据列表

Angular X中使用ngrx的方法详解(附源码)

点击info按钮  获取详细详细

Angular X中使用ngrx的方法详解(附源码) 

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.模块源代码

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对三水点靠木的支持。

Javascript 相关文章推荐
Javascript Request获取请求参数如何实现
Nov 28 Javascript
基于SVG的web页面图形绘制API介绍及编程演示
Jun 28 Javascript
requireJS使用指南
Apr 27 Javascript
浅谈jQuery this和$(this)的区别及获取$(this)子元素对象的方法
Nov 29 Javascript
JS实现滑动门效果的方法详解
Dec 19 Javascript
将Sublime Text 3 添加到右键中的简单方法
Dec 12 Javascript
原生JS实现的双色球功能示例
Feb 02 Javascript
bing Map 在vue项目中的使用详解
Apr 09 Javascript
vue-baidu-map 进入页面自动定位的解决方案(推荐)
Apr 28 Javascript
JS实现的点击按钮图片上下滚动效果示例
Jan 28 Javascript
Vue组件通信中非父子组件传值知识点总结
Dec 05 Javascript
vue/cli 配置动态代理无需重启服务的方法
May 20 Vue.js
angular实现spa单页面应用实例
Jul 10 #Javascript
JavaScript 程序错误Cannot use 'in' operator to search的解决方法
Jul 10 #Javascript
JS 判断某变量是否为某数组中的一个值的3种方法(总结)
Jul 10 #Javascript
vue.js实现备忘录功能的方法
Jul 10 #Javascript
AugularJS从入门到实践(必看篇)
Jul 10 #Javascript
基于easyui checkbox 的一些操作处理方法
Jul 10 #Javascript
AngularJS实用基础知识_入门必备篇(推荐)
Jul 10 #Javascript
You might like
PHP4实际应用经验篇(8)
2006/10/09 PHP
php switch语句多个值匹配同一代码块的实现
2014/03/03 PHP
PHP不用递归实现无限分级的例子分享
2014/04/18 PHP
php把大写命名转换成下划线分割命名
2015/04/27 PHP
php mysql_list_dbs()函数用法示例
2017/03/29 PHP
Javascript实现关联数据(Linked Data)查询及注意细节
2013/02/22 Javascript
php 中序列化和json使用介绍
2013/07/08 Javascript
JavaScript检测弹出窗口是否已经关闭的方法
2015/03/24 Javascript
JS+CSS实现美化的下拉列表框效果
2015/08/11 Javascript
jquery基础知识第一讲之认识jquery
2016/03/17 Javascript
JavaScript中const、var和let区别浅析
2016/10/11 Javascript
SpringMVC简单整合Angular2的示例
2017/07/31 Javascript
详解JS数组Reduce()方法详解及高级技巧
2017/08/18 Javascript
使用vue-resource进行数据交互的实例
2017/09/02 Javascript
3种vue组件的书写形式
2017/11/29 Javascript
JS构造一个html文本内容成文件流形式发送到后台
2018/07/31 Javascript
vue项目使用$router.go(-1)返回时刷新原来的界面操作
2020/07/26 Javascript
在Python的Flask框架中构建Web表单的教程
2016/06/04 Python
详解python之配置日志的几种方式
2017/05/22 Python
浅谈关于Python3中venv虚拟环境
2018/08/01 Python
python实现大战外星人小游戏实例代码
2019/12/26 Python
Python 如何批量更新已安装的库
2020/05/26 Python
Python使用pyenv实现多环境管理
2021/02/05 Python
HTML5跳转小程序wx-open-launch-weapp的示例代码
2020/07/16 HTML / CSS
加拿大著名时装品牌:SOIA & KYO
2016/08/23 全球购物
猫咪家具:CatsPlay
2018/11/03 全球购物
读书演讲主持词
2014/03/18 职场文书
学校就业推荐信范文
2014/05/19 职场文书
个人作风建设自查报告
2014/10/22 职场文书
小学少先队辅导员述职报告
2015/01/10 职场文书
财务个人年度总结范文
2015/02/26 职场文书
2015秋季幼儿园开学寄语
2015/03/25 职场文书
公司辞职信模板
2015/05/13 职场文书
小学生禁毒教育心得体会
2016/01/15 职场文书
学习焦裕禄先进事迹心得体会
2016/01/23 职场文书
Python 多线程之threading 模块的使用
2021/04/14 Python