欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-11-26 14:30:25
前言 ngrx 是 angular框架的状态容器,提供可预测化的状态管理。下面话不多说,来一起看看详细的介绍: 1.首先创建一个可路由访问的模块 这里命名为:demop...

前言

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

总结

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