angular状态管理方案(ngrx)

2023-12-16 03:15

本文主要是介绍angular状态管理方案(ngrx),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

完全基于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的方法。

这篇关于angular状态管理方案(ngrx)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/498897

相关文章

前端下载文件时如何后端返回的文件流一些常见方法

《前端下载文件时如何后端返回的文件流一些常见方法》:本文主要介绍前端下载文件时如何后端返回的文件流一些常见方法,包括使用Blob和URL.createObjectURL创建下载链接,以及处理带有C... 目录1. 使用 Blob 和 URL.createObjectURL 创建下载链接例子:使用 Blob

Vuex Actions多参数传递的解决方案

《VuexActions多参数传递的解决方案》在Vuex中,actions的设计默认只支持单个参数传递,这有时会限制我们的使用场景,下面我将详细介绍几种处理多参数传递的解决方案,从基础到高级,... 目录一、对象封装法(推荐)二、参数解构法三、柯里化函数法四、Payload 工厂函数五、TypeScript

SpringSecurity JWT基于令牌的无状态认证实现

《SpringSecurityJWT基于令牌的无状态认证实现》SpringSecurity中实现基于JWT的无状态认证是一种常见的做法,本文就来介绍一下SpringSecurityJWT基于令牌的无... 目录引言一、JWT基本原理与结构二、Spring Security JWT依赖配置三、JWT令牌生成与

基于Python和MoviePy实现照片管理和视频合成工具

《基于Python和MoviePy实现照片管理和视频合成工具》在这篇博客中,我们将详细剖析一个基于Python的图形界面应用程序,该程序使用wxPython构建用户界面,并结合MoviePy、Pill... 目录引言项目概述代码结构分析1. 导入和依赖2. 主类:PhotoManager初始化方法:__in

Vue3使用router,params传参为空问题

《Vue3使用router,params传参为空问题》:本文主要介绍Vue3使用router,params传参为空问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐... 目录vue3使用China编程router,params传参为空1.使用query方式传参2.使用 Histo

Java图片压缩三种高效压缩方案详细解析

《Java图片压缩三种高效压缩方案详细解析》图片压缩通常涉及减少图片的尺寸缩放、调整图片的质量(针对JPEG、PNG等)、使用特定的算法来减少图片的数据量等,:本文主要介绍Java图片压缩三种高效... 目录一、基于OpenCV的智能尺寸压缩技术亮点:适用场景:二、JPEG质量参数压缩关键技术:压缩效果对比

关于WebSocket协议状态码解析

《关于WebSocket协议状态码解析》:本文主要介绍关于WebSocket协议状态码的使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录WebSocket协议状态码解析1. 引言2. WebSocket协议状态码概述3. WebSocket协议状态码详解3

SpringBoot首笔交易慢问题排查与优化方案

《SpringBoot首笔交易慢问题排查与优化方案》在我们的微服务项目中,遇到这样的问题:应用启动后,第一笔交易响应耗时高达4、5秒,而后续请求均能在毫秒级完成,这不仅触发监控告警,也极大影响了用户体... 目录问题背景排查步骤1. 日志分析2. 性能工具定位优化方案:提前预热各种资源1. Flowable

CSS Padding 和 Margin 区别全解析

《CSSPadding和Margin区别全解析》CSS中的padding和margin是两个非常基础且重要的属性,它们用于控制元素周围的空白区域,本文将详细介绍padding和... 目录css Padding 和 Margin 全解析1. Padding: 内边距2. Margin: 外边距3. Padd

CSS will-change 属性示例详解

《CSSwill-change属性示例详解》will-change是一个CSS属性,用于告诉浏览器某个元素在未来可能会发生哪些变化,本文给大家介绍CSSwill-change属性详解,感... will-change 是一个 css 属性,用于告诉浏览器某个元素在未来可能会发生哪些变化。这可以帮助浏览器优化