angular状态管理方案(ngrx)

news/2025/2/22 2:48:04/

完全基于redux的ngrx方案,我们看看在angular中如何实现。通过一个简单的计数器例子梳理下整个流程

一 安装 :npm i  ngrx/store

这里特别要注意一点:安装 @ngrx/store的时候会出现和angular版本不一致的问题

所以检查一下@angular/core的版本和ngrx/store的版本是否一致,如果不一致升级angular,

 ng update @angular/core@17.0.0 --force。最好是删除node_modules目录重新下载。保证安装正常,版本一致

二 创建store目录,并且创建如下几个文件:

(1)actions.ts

   (2) reducers.ts

   (3)  state.ts

//state.tsexport interface AppState{count:number;
}   //actions.ts
export const INSCRES="INSCRES"
export const DESCRES="DESCRES"
export const RESET="RESET"//reduces:import {Action} from "@ngrx/store"
import {INSCRES,DESCRES,RESET} from "./actions"const initalState=0;
export function counterReducer(state:number=initalState,action:Action){switch(action.type){case INSCRES:return state+1;case DESCRES:return state-1case RESET:return 0default:return state}}

(4) 页面中注入:注意angular中使用store和react稍有不同。没有createStore(reducer)然后根组件注入的过程,而是在具体页面里直接注入到constructor中,我们以news页面为例,


import { Component, ElementRef, ViewChild } from '@angular/core';
import {INSCRES,DESCRES,RESET} from "../../store/reducer"
import {Store,select} from "@ngrx/store"
import { Observable } from 'rxjs';interface AppState{count:number
}@Component({selector: 'app-news',templateUrl: './news.component.html',styleUrls: ['./news.component.less']
})export class NewsComponent {count:Observable<number>constructor(public http:HttpClient,private store:Store<AppState>){let stream=store.pipe(select('count'))stream.subscribe(res=>{console.log("res:",res)})this.count=store.pipe(select('count'))}increasement(){this.store.dispatch({type:INSCRES})}decreasement(){this.store.dispatch({type:DESCRES})}reset(){this.store.dispatch({type:RESET})}}

然后在具体的页面中使用count:

 <button (click)="increasement()">增加increase</button><div>counter :{{count | async }}</div><button (click)="decreasement()">减少increase</button><button (click)="reset()">reset counter</button>

整体来看和react中使用redux并没有太大的差异。唯一的差异就是在react中需要定义store(let store=createStore(state,)),angular中直接通过在页面中注入的方式完成。

二:actions也可以是函数,我们可以改造下actions

//actions :注意这里需要用Injectable
import {Injectable} from "@angular/core"export const INSCRES="INSCRES"
export const DESCRES="DESCRES"
export const RESET="RESET"@Injectable()
export  class CountAction{add(){return {type:INSCRES}}}

此时我们需要向app.moudule.ts中作相应修改:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';import {CountAction} from "./store/actions"import { AppComponent } from './app.component';
import { NZ_I18N } from 'ng-zorro-antd/i18n';
import { zh_CN } from 'ng-zorro-antd/i18n';import { HomeComponent } from './pages/home/home.component';
import { AppRouteModule } from './app-route.module';import { StoreModule } from '@ngrx/store';registerLocaleData(zh);@NgModule({declarations: [AppComponent,LayoutComponent,HomeComponent,],providers: [{provide:CountAction},{ provide: [NZ_I18N, UrlSerializer], useValue: zh_CN },{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptorInterceptor, multi: true },],bootstrap: [AppComponent],imports: [BrowserModule,FormsModule,AppRouteModule,StoreModule.forRoot({count:counterReducer}, {}),]
})
export class AppModule { }

注意这里我们给providers添加了counterAction,以便在所有页面都可以注入countActions

回到页面本身:

import { Component, OnInit } from '@angular/core';
import { Observable, Observer } from 'rxjs';
import{CountAction} from "../../store/actions"
import {Store,select} from "@ngrx/store"interface AppState{count:number
}@Component({selector: 'app-home',templateUrl: './home.component.html',styleUrls: ['./home.component.less']
})
export class HomeComponent {count:Observable<number>constructor(private store:Store<AppState>,private action:CountAction){this.count=this.store.pipe(select('count'))increasement(){this.store.dispatch(this.action.add())}}

这里逻辑的实现和之前一致,唯一的区别就是我们countAction直接注到了counstor里,然后在具体的执行函数中直接actiions的方法。


http://www.ppmy.cn/news/1264045.html

相关文章

Apache Ofbiz XML-RPC RCE漏洞复现(CVE-2023-49070)

0x01 产品简介 Apache OFBiz是一个开源的企业资源规划(ERP)系统,提供了多种商业功能和模块。 0x02 漏洞概述 漏洞成因 2020年,为修复 CVE-2020-9496 增加权限校验,存在绕过。2021年,增加 Filter 用于拦截 XML-RPC 中的恶意请求,存在绕过。2023年四月,彻底删除 xmlrp…

Matlab 点云收缩L1中值(Weiszfeld算法)

文章目录 一、简介二、实现代码三、实现效果参考资料一、简介 对于之前的加权均值收缩方式,它存在一个很大的缺点,即容易受到噪声的影响,因此这里我们采用另一种统计学方案:L1中值。其形式如下所示: 其中 x i x_i

TCP传输数据的确认机制

实际的TCP收发数据的过程是双向的。 TCP采用这样的方式确认对方是否收到了数据&#xff0c;在得到对方确认之前&#xff0c;发送过的包都会保存在发送缓冲区中。如果对方没有返回某些包对应的ACK号&#xff0c;那么就重新发送这些包。 这一机制非常强大。通过这一机制&#xf…

mysql面试题——日志

一&#xff1a;为什么需要REDO日志 缓冲池可以帮助我们消除CPU和磁盘之间的鸿沟&#xff0c;checkpoint机制可以保证数据的最终落盘&#xff0c;然而由于checkpoint 并不是每次变更的时候就触发 的&#xff0c;而是master线程隔一段时间去处理的。所以最坏的情况就是事务提交后…

C语言有哪些预处理操作?

C语言的预处理是在编译之前对源代码进行处理的阶段&#xff0c;它主要由预处理器完成。预处理器是一个独立的程序&#xff0c;它负责对源代码进行一些文本替换和处理&#xff0c;生成经过预处理的代码。以下是C语言预处理的一些重要特性&#xff1a; 1&#xff0c;头文件包含 #…

常用方法和调度

Thread类的方法 1、start()&#xff1a; ①启动当前线程&#xff08;新的线程&#xff09; ②调用当前线程的run&#xff08; &#xff09;。 2. run()&#xff1a; ①通常须要进行重写 ②将创建线程要执行的操作声明在此方法中。 3.、currentThread()&#xff1a; ①静态方法…

【2023传智杯-新增场次】第六届传智杯程序设计挑战赛AB组-ABC题复盘解题分析详解【JavaPythonC++解题笔记】

本文仅为【2023传智杯-第二场】第六届传智杯程序设计挑战赛-题目解题分析详解的解题个人笔记,个人解题分析记录。 本文包含:第六届传智杯程序设计挑战赛题目、解题思路分析、解题代码、解题代码详解 文章目录 一.前言二.赛题题目A题题目-B题题目-C题题目-二.赛题题解A题题解-…

Java - Synchronized的锁升级之路

Synchronized锁 Synchronized在Java JVM里的实现是基于进入和退出Monitor对象来实现方法同步和代码块同步的 monitor enter指令是在编译后插入到同步代码块的开始位置 而monitor exit是插入到方法结束处和异常处 JVM要保证每个monitor enter必须有对应的monitor exit与之配对。…