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

 更新时间:2017年07月10日 08:33:59   作者:迷惘却坚定  
ngrx是一套利用RxJS的类库,下面这篇文章主要给大家介绍了关于Angular X中使用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.模块源代码

下载地址

总结

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

相关文章

  • 学习Angularjs分页指令

    学习Angularjs分页指令

    这篇文章主要和大家一起学习Angularjs分页指令,代码很详细,文章结构紧凑,感兴趣的小伙伴们可以参考一下
    2016-07-07
  • 利用Angular.js限制textarea输入的字数

    利用Angular.js限制textarea输入的字数

    相信在大家已经学习了足够多关于AngularJS的知识后,就可以开始创建第一个AngularJS应用程序,这篇文章通过示例给大家介绍如何利用Angular.js限制textarea输入的字数,有需要的朋友们可以参考借鉴,下面来一起看看吧。
    2016-10-10
  • AngularJS中ng-options实现下拉列表的数据绑定方法

    AngularJS中ng-options实现下拉列表的数据绑定方法

    今天小编就为大家分享一篇AngularJS中ng-options实现下拉列表的数据绑定方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-08-08
  • angular异步验证器防抖实例详解

    angular异步验证器防抖实例详解

    在实际工作中,我们经常需要一个基于后端API验证值的验证器,下面这篇文章主要给大家介绍了关于angular异步验证器防抖的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考下
    2022-03-03
  • 详解AngularJS中的http拦截

    详解AngularJS中的http拦截

    这篇文章主要为大家详细介绍了AngularJS中的http拦截,$http服务允许我们与服务端交互,有时候我们希望在发出请求之前以及收到响应之后做些事情。即http拦截,需要的朋友可以参考下
    2016-02-02
  • Angularjs 实现一个幻灯片示例代码

    Angularjs 实现一个幻灯片示例代码

    本文主要介绍Angularjs 写一个幻灯片的知识,这里整理了详细的资料,及实现代码和实现效果图有需要的小伙伴可以参考下
    2016-09-09
  • Angular中$cacheFactory的作用和用法实例详解

    Angular中$cacheFactory的作用和用法实例详解

    $cacheFactory是一个为Angular服务生产缓存对象的服务。接下来通过本文给大家介绍Angular中$cacheFactory的作用和用法实例详解,非常不错,感兴趣的朋友一起看下吧
    2016-08-08
  • AngularJS $injector 依赖注入详解

    AngularJS $injector 依赖注入详解

    这篇文章主要介绍了AngularJS $injector 依赖注入的相关资料,需要的朋友可以参考下
    2016-09-09
  • Angular 多级路由实现登录页面跳转(小白教程)

    Angular 多级路由实现登录页面跳转(小白教程)

    这篇文章主要介绍了Angular 多级路由实现登录页面跳转(小白教程),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-11-11
  • Angular搜索场景中使用rxjs的操作符处理思路

    Angular搜索场景中使用rxjs的操作符处理思路

    这篇文章主要介绍了Angular搜索场景中使用rxjs的操作符处理思路,主要的思路就是通过Subject来发送过滤条件,这样就可以使用rxjs的各种操作符,可以快捷很多。需要的朋友可以参考下
    2018-05-05

最新评论