Angular X中使用ngrx的方法详解(附源码)
发布时间 - 2026-01-11 02:15:24 点击率:次前言

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.模块源代码
下载地址
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对的支持。
# angular2
# ngrx
# angular8和ngrx8结合使用的步骤介绍
# Angular 与 Component store实践示例
# angularjs实现table表格td单元格单击变输入框/可编辑状态示例
# angular 未登录状态拦截路由跳转的方法
# Angular5中状态管理的实现
# Angular Ngrx Store应用程序状态典型示例详解
# 是一个
# 有个
# 下载地址
# 是从
# 这篇文章
# 涉及到
# 谢谢大家
# 多说
# 命名为
# 创建一个
# 源代码
# 解下
# 实现了
# 有疑问
# save
# install
# npm
# store
# tag
# effects
相关栏目:
【
网站优化151355 】
【
网络推广146373 】
【
网络技术251813 】
【
AI营销90571 】
相关推荐:
如何为不同团队 ID 动态生成多个独立按钮
Laravel如何实现用户注册和登录?(Auth脚手架指南)
浅述节点的创建及常见功能的实现
Windows10电脑怎么设置虚拟光驱_Win10右键装载ISO镜像文件
佛山网站制作系统,佛山企业变更地址网上办理步骤?
5种Android数据存储方式汇总
Laravel怎么创建自己的包(Package)_Laravel扩展包开发入门到发布
ChatGPT回答中断怎么办 引导AI继续输出完整内容的方法
PHP的CURL方法curl_setopt()函数案例介绍(抓取网页,POST数据)
专业型网站制作公司有哪些,我设计专业的,谁给推荐几个设计师兼职类的网站?
南京网站制作费用,南京远驱官方网站?
如何在阿里云高效完成企业建站全流程?
在线教育网站制作平台,山西立德教育官网?
深圳网站制作培训,深圳哪些招聘网站比较好?
Laravel定时任务怎么设置_Laravel Crontab调度器配置
北京网站制作费用多少,建立一个公司网站的费用.有哪些部分,分别要多少钱?
Laravel怎么进行数据库回滚_Laravel Migration数据库版本控制与回滚操作
LinuxShell函数封装方法_脚本复用设计思路【教程】
Laravel怎么连接多个数据库_Laravel多数据库连接配置
高防服务器:AI智能防御DDoS攻击与数据安全保障
如何在腾讯云免费申请建站?
Android仿QQ列表左滑删除操作
如何获取PHP WAP自助建站系统源码?
Android实现代码画虚线边框背景效果
Laravel广播系统如何实现实时通信_Laravel Reverb与WebSockets实战教程
实例解析Array和String方法
高端云建站费用究竟需要多少预算?
canvas 画布在主流浏览器中的尺寸限制详细介绍
如何确保FTP站点访问权限与数据传输安全?
Laravel如何编写单元测试和功能测试?(PHPUnit示例)
如何在景安服务器上快速搭建个人网站?
Laravel Pest测试框架怎么用_从PHPUnit转向Pest的Laravel测试教程
猪八戒网站制作视频,开发一个猪八戒网站,大约需要多少?或者自己请程序员,需要什么程序员,多少程序员能完成?
网站建设要注意的标准 促进网站用户好感度!
如何用手机制作网站和网页,手机移动端的网站能制作成中英双语的吗?
Windows10如何删除恢复分区_Win10 Diskpart命令强制删除分区
JavaScript如何实现错误处理_try...catch如何捕获异常?
Win10如何卸载预装Edge扩展_Win10卸载Edge扩展教程【方法】
javascript中数组(Array)对象和字符串(String)对象的常用方法总结
Midjourney怎样加参数调细节_Midjourney参数调整技巧【指南】
Laravel队列由Redis驱动怎么配置_Laravel Redis队列使用教程
Laravel全局作用域是什么_Laravel Eloquent Global Scopes应用指南
千问怎样用提示词获取健康建议_千问健康类提示词注意事项【指南】
Laravel如何实现数据导出到CSV文件_Laravel原生流式输出大数据量CSV【方案】
Laravel如何配置.env文件管理环境变量_Laravel环境变量使用与安全管理
Laravel如何使用Livewire构建动态组件?(入门代码)
Python制作简易注册登录系统
如何用JavaScript实现文本编辑器_光标和选区怎么处理
Win11怎么更改系统语言为中文_Windows11安装语言包并设为显示语言
javascript和jQuery中的AJAX技术详解【包含AJAX各种跨域技术】

