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

相关文章

基于 HTML5 Canvas 实现图片旋转与下载功能(完整代码展示)

《基于HTML5Canvas实现图片旋转与下载功能(完整代码展示)》本文将深入剖析一段基于HTML5Canvas的代码,该代码实现了图片的旋转(90度和180度)以及旋转后图片的下载... 目录一、引言二、html 结构分析三、css 样式分析四、JavaScript 功能实现一、引言在 Web 开发中,

CSS place-items: center解析与用法详解

《CSSplace-items:center解析与用法详解》place-items:center;是一个强大的CSS简写属性,用于同时控制网格(Grid)和弹性盒(Flexbox)... place-items: center; 是一个强大的 css 简写属性,用于同时控制 网格(Grid) 和 弹性盒(F

CSS实现元素撑满剩余空间的五种方法

《CSS实现元素撑满剩余空间的五种方法》在日常开发中,我们经常需要让某个元素占据容器的剩余空间,本文将介绍5种不同的方法来实现这个需求,并分析各种方法的优缺点,感兴趣的朋友一起看看吧... css实现元素撑满剩余空间的5种方法 在日常开发中,我们经常需要让某个元素占据容器的剩余空间。这是一个常见的布局需求

CSS Anchor Positioning重新定义锚点定位的时代来临(最新推荐)

《CSSAnchorPositioning重新定义锚点定位的时代来临(最新推荐)》CSSAnchorPositioning是一项仍在草案中的新特性,由Chrome125开始提供原生支持需... 目录 css Anchor Positioning:重新定义「锚定定位」的时代来了! 什么是 Anchor Pos

CSS中的Static、Relative、Absolute、Fixed、Sticky的应用与详细对比

《CSS中的Static、Relative、Absolute、Fixed、Sticky的应用与详细对比》CSS中的position属性用于控制元素的定位方式,不同的定位方式会影响元素在页面中的布... css 中的 position 属性用于控制元素的定位方式,不同的定位方式会影响元素在页面中的布局和层叠关

HTML5 getUserMedia API网页录音实现指南示例小结

《HTML5getUserMediaAPI网页录音实现指南示例小结》本教程将指导你如何利用这一API,结合WebAudioAPI,实现网页录音功能,从获取音频流到处理和保存录音,整个过程将逐步... 目录1. html5 getUserMedia API简介1.1 API概念与历史1.2 功能与优势1.3

全面解析HTML5中Checkbox标签

《全面解析HTML5中Checkbox标签》Checkbox是HTML5中非常重要的表单元素之一,通过合理使用其属性和样式自定义方法,可以为用户提供丰富多样的交互体验,这篇文章给大家介绍HTML5中C... 在html5中,Checkbox(复选框)是一种常用的表单元素,允许用户在一组选项中选择多个项目。本

HTML5 搜索框Search Box详解

《HTML5搜索框SearchBox详解》HTML5的搜索框是一个强大的工具,能够有效提升用户体验,通过结合自动补全功能和适当的样式,可以创建出既美观又实用的搜索界面,这篇文章给大家介绍HTML5... html5 搜索框(Search Box)详解搜索框是一个用于输入查询内容的控件,通常用于网站或应用程

CSS3中的字体及相关属性详解

《CSS3中的字体及相关属性详解》:本文主要介绍了CSS3中的字体及相关属性,详细内容请阅读本文,希望能对你有所帮助... 字体网页字体的三个来源:用户机器上安装的字体,放心使用。保存在第三方网站上的字体,例如Typekit和Google,可以link标签链接到你的页面上。保存在你自己Web服务器上的字

使用jenv工具管理多个JDK版本的方法步骤

《使用jenv工具管理多个JDK版本的方法步骤》jenv是一个开源的Java环境管理工具,旨在帮助开发者在同一台机器上轻松管理和切换多个Java版本,:本文主要介绍使用jenv工具管理多个JD... 目录一、jenv到底是干啥的?二、jenv的核心功能(一)管理多个Java版本(二)支持插件扩展(三)环境隔