如何在AngularX 中 使用ngrx
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 {
}
整体代码结构如下:

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

2.安装ngrx
npm install @ngrx/core --save
npm install @ngrx/store --save
npm install @ngrx/effects --save
@ngrx/store是一个旨在提高写性能的控制状态的容器
3.使用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.运行效果
初始化时候获取数据列表

点击info按钮 获取详细详细

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.模块源代码 下载
9.我的微信公众号。

如何在AngularX 中 使用ngrx的更多相关文章
- 我是如何在SQLServer中处理每天四亿三千万记录的
首先声明,我只是个程序员,不是专业的DBA,以下这篇文章是从一个问题的解决过程去写的,而不是一开始就给大家一个正确的结果,如果文中有不对的地方,请各位数据库大牛给予指正,以便我能够更好的处理此次业务. ...
- 如何在SpringBoot中使用JSP ?但强烈不推荐,果断改Themeleaf吧
做WEB项目,一定都用过JSP这个大牌.Spring MVC里面也可以很方便的将JSP与一个View关联起来,使用还是非常方便的.当你从一个传统的Spring MVC项目转入一个Spring Boot ...
- 如何在latex 中插入EPS格式图片
如何在latex 中插入EPS格式图片 第一步:生成.eps格式的图片 1.利用visio画图,另存为pdf格式的图片 利用Adobe Acrobat裁边,使图片大小合适 另存为.eps格式,如下图所 ...
- 如何正确的使用json?如何在.Net中使用json?
什么是json json是一种轻量级的数据交换格式,由N组键值对组成的字符串,完全独立于语言的文本格式. 为什么要使用json 在很久很久以前,调用第三方API时,我们通常是采用xml进行数据交互,但 ...
- [原创]如何在Parcelable中使用泛型
[原创]如何在Parcelable中使用泛型 实体类在实现Parcelable接口时,除了要实现它的几个方法之外,还另外要定义一个静态常量CREATOR,如下例所示: public static cl ...
- 如何在springMVC 中对REST服务使用mockmvc 做测试
如何在springMVC 中对REST服务使用mockmvc 做测试 博客分类: java 基础 springMVCmockMVC单元测试 spring 集成测试中对mock 的集成实在是太棒了!但 ...
- 如何在tomcat中如何部署java EE项目
如何在tomcat中如何部署java EE项目 1.直接把项目复制到Tomcat安装目录的webapps目录中,这是最简单的一种Tomcat项目部署的方法,也是初学者最常用的方法.2.在tomcat安 ...
- 【转】我是如何在SQLServer中处理每天四亿三千万记录的
原文转自:http://blog.jobbole.com/80395/ 首先声明,我只是个程序员,不是专业的DBA,以下这篇文章是从一个问题的解决过程去写的,而不是一开始就给大家一个正确的结果,如果文 ...
- 如何在JAVA中实现一个固定最大size的hashMap
如何在JAVA中实现一个固定最大size的hashMap 利用LinkedHashMap的removeEldestEntry方法,重载此方法使得这个map可以增长到最大size,之后每插入一条新的记录 ...
随机推荐
- 判断网站URL是否正常访问脚本
#!/bin/bash [ -f /etc/init.d/functions ] && . /etc/init.d/functions function usage(){ echo & ...
- Redis数据类型之Hash(二)
前言: Redis hash是一个String类型的field和value的映射表.添加.删除操作复杂度平均为O(1),为什么是平均呢?因为Hash的内部结构包含zipmap和hash两种.hash特 ...
- Selenium基础知识
本人博客文章网址:https://www.peretang.com/basic-knowledge-of-selenium/ 什么是Selenium Selenium是一个自动化测试工具 是一组不同的 ...
- 《物联网框架ServerSuperIO教程》-20.网络通讯控制器分组,提高交互的负载平衡能力。v3.6.6 版本发布
20.1 概述 ServerSuperIO原来在网络通讯模式下,只有一个网络控制器,在自控模式.并发模式和单例模式下时都是异步处理返回的数据,并不会出现性能问题.但是在轮询模式下,一个网络控制 ...
- APUE-文件和目录(三)函数chown 和lchown
下面的几个chown函数可用于更改文件的用户ID和组ID.如果两个参数owner或group中的任意一个是-1,则对应的ID不变. #include<unistd.h> int chown ...
- unity3D:游戏分解之角色移动和相机跟随
游戏中,我们经常会有这样的操作,点击场景中某个位置,角色自动移动到那个位置,同时角色一直是朝向那个位置移动的,而且相机也会一直跟着角色移动.有些游戏,鼠标滑动屏幕,相机就会围绕角色旋转. ...
- java基础(九章)
一.理解查询的机制 客户端应用程序(c/s.b/s)向后台服务器的DB发送一条select语句进行查询操作,会将结果集(虚拟表)返回到客户端应用程序 二.select语句 1.查询表中的全部列和行 s ...
- python基础操作_元组_字典操作
#元组'''元组是不可变的列表,不能改.取值和列表一样'''tp=(1,2,3)tp1=('127.0.0.1','3307')#元组只有count 和index两个方法.lis=['127.0.0. ...
- 简单两步快速学会使用Mybatis-Generator自动生成entity实体、dao接口和简单mapper映射(用mysql和oracle举例)
前言: mybatis-generator是根据配置文件中我们配置的数据库连接参数自动连接到数据库并根据对应的数据库表自动的生成与之对应mapper映射(比如增删改查,选择性增删改查等等简单语句)文件 ...
- openjdk8之编译和debug
系统环境为ubuntu 16.04,uname -a: Linux ddy-Aspire-V5-573G 4.4.0-21-generic #37-Ubuntu SMP Mon Apr 18 18:3 ...