NGRX 的信号存储 - 主要概念细分
来源:dev.to
时间:2024-07-23 10:46:06 161浏览 收藏
golang学习网今天将给大家带来《NGRX 的信号存储 - 主要概念细分》,感兴趣的朋友请继续看下去吧!以下内容将会涉及到等等知识点,如果你是正在学习文章或者已经是大佬级别了,都非常欢迎也希望大家都能给我建议评论哈~希望能帮助到大家!

特征
- 基于信号
- 函数式和声明式
- 用于本地或全局状态管理
- 可通过自定义功能进行扩展
与 ngrx 全球商店相比如何?
- 更轻量级和简化的api
- 不必太担心数据流
- 似乎更难误用,比如重用动作
- 更容易扩展
ngrx signal store 的创建者,marko stanimirovic 在这里描述了 ngrx signalstore:深入了解 angular 中基于信号的状态管理
基于类的状态管理限制:
- 类型:不可能定义强类型的动态类属性或方法
- tree-shaking:未使用的类方法不会从最终包中删除
- 扩展性:不支持多重继承。
- 模块化:可以将选择器、更新器和效果拆分为不同的类,但不提供开箱即用的
让我们通过代码示例来探索商店的 api。我们将使用一个包含产品列表和过滤功能的项目。
创建一个signalstore
- signalstore 函数返回一个适合注入并在需要使用的地方提供的可注入服务。
import { signalstore } from "@ngrx/signals";
export const productstore = signalstore( … );
提供状态withstate
与迄今为止的任何 ngrx store 一样,可以使用函数 withstate 来提供初始状态,该函数接受对象文字、记录或工厂函数(用于创建动态初始状态)作为输入。
import { signalstore, withstate } from "@ngrx/signals";
const initialproductstate: productstate = { products: [] };
export const productstore = signalstore(
withstate(initialproductstate);
);
计算状态withcompated
- 构建在计算函数之上,从存储创建派生状态(计算状态)
import { signalstore, withcomputed, withstate } from "@ngrx/signals";
export const productstore = signalstore(
withstate(initialproductstate),
withcomputed(({products}) => ({
averageprice: computed(() => {
const total = products().reduce((acc, p) => acc + p.price, 0);
return total / products().length;
})
})),
使用方法执行操作
- 这是定义商店运营的地方
- 这些可以是更新存储或根据其当前状态执行某些操作的方法
import { signalstore, withcomputed, withstate, withmethods } from "@ngrx/signals";
export const productstore = signalstore(
withstate(initialproductstate),
withcomputed(({products}) => ({
averageprice: computed(() => {
const total = products().reduce((acc, p) => acc + p.price, 0);
return total / products().length;
})
})),
// crud operations
withmethods((store,
productservice = inject(productservice),
) => ({
loadproducts: () => {
const products = tosignal(productservice.loadproducts())
patchstate(store, { products: products() })
},
addproduct: (product: product) => {
patchstate(store, { products: [...store.products(), product] });
},
// ...
})),
withmethods & withcompulated 获取工厂函数并返回可以使用存储访问的方法和计算信号的字典。它们还在注入上下文中运行,这使得可以将依赖项注入到它们中。
用 hooks 挂钩
- store的生命周期方法,目前有
- oninit和ondestroy方法
import { withhooks } from "@ngrx/signals";
export const productstore = signalstore(
withhooks((store) => ({
oninit() {
// load products when the store is initialized
store.loadproducts();
},
})),
);
使用实体管理集合
- 当必须管理“产品、用户、客户等”等数据时使用它,其中该功能需要 crud 操作
- 它提供了一组 api 来管理集合,例如:
- addentity、setentity、remoteentity。
export const productstorewithentities = signalstore(
withentities<product>(),
// crud operations
withmethods((store,
productservice = inject(productservice),
) => ({
loadproducts: () => {
const products = tosignal(productservice.loadproducts())();
patchstate(store, setallentities(products || []));
},
updateproduct: (product: product) => {
productservice.updateproduct(product);
patchstate(store, setentity(product));
},
})),
可以添加以“with”开头的多个功能,但它们只能访问之前定义的功能。
使用signalstorefeature 创建自定义功能
signalstorefeature - 用于扩展商店的功能。对于大型企业应用程序来说,商店可能会变得复杂且难以管理。在为项目编写功能和组件时,拆分得越好、越细,就越容易管理、维护代码和为其编写测试。
但是,考虑到 signalstore 提供的 api,除非相应地拆分代码,否则存储可能会变得难以管理。 signalstorefeature 适合将功能(或组件)的特定功能提取到独立的可测试函数中,该函数可能(并且理想情况下)可以在其他商店中重用。
export const productstore = signalstore(
// previous defined state and methods
// externalizing filtering options
withfilteringoptions(),
);
export function withfilteringoptions() {
return signalstorefeature(
// filtering operations
withmethods(() => ({
getproductsbetweenpricerange: (lowprice: number, highprice: number, products: array<product>, ) => {
return products.filter(p => p.price >= lowprice && p.price <= highprice);
},
getproductsbycategory: (category: string, products: array<product>) => {
return products.filter(p => p.category === category);
},
})),
);
}
现在是 signalstorefeature 的示例,它展示了跨多个商店重用 signalstorefeature 的可能性。
从“@ngrx/signals”导入{ patchstate, signalstorefeature, withmethods };
export function withCrudOperations() {
return signalStoreFeature(
withMethods((store) => ({
load: (crudService: CrudOperations) => crudService.load(),
update: (crudableObject: CRUD, crudService: CrudOperations) => {
crudService.update(crudableObject);
patchState(store, setEntity(crudableObject));
},
}),
));
}
export interface CrudOperations {
load(): void;
update(crudableObject: CRUD): void;
}
// Product & Customer services must extend the same interface.
export class ProductService implements CrudOperations {
load(): void {
console.log('load products');
}
update(): void {
console.log('update products');
}
}
export class CustomerService implements CrudOperations {
load(): void {
console.log('load customers');
}
update(): void {
console.log('update customers');
}
}
// and now let’s add this feature in our stores
export const ProductStore = signalStore(
withCrudOperations(),
);
export const CustomerStore = signalStore(
withCrudOperations(),
);
ngrx 工具包实用程序包
由于易于扩展,已经有一个名为 ngrx-toolkit 的实用程序包,旨在向信号存储添加有用的工具。
注入signalstore
{providedin: ‘root’} 或在组件、服务、指令等的提供者数组中
深度信号
- 嵌套状态属性读取为信号,按需延迟生成
- 信号api的
- set和update的替代api用于更新商店的状态,只需要提供我们想要更改的值
- 实用方法,有助于将 rxjs 与 signalstore 或 signalstate 一起使用
signalstate 的更轻量级替代方案
- signalstate 提供了一种以简洁和简约的方式管理基于信号的状态的替代方法。
对于大型应用程序来说,它的可靠性还有待证明,尤其是作为全球商店应用时。
目前我认为这是对默认 signal api 的一个很好的补充,使其成为管理的一个不错的选择:
- 组件级状态
- 基于特征的状态
https://www.stefanos-lignos.dev/posts/ngrx-signals-store
https://www.angulararchitects.io/blog/the-new-ngrx-signal-store-for-angular-2-1-flavors/(关于该主题的 4 篇文章)
https://ngrx.io/guide/signals
今天关于《NGRX 的信号存储 - 主要概念细分》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!
-
502 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
442 收藏
-
483 收藏
-
157 收藏
-
302 收藏
-
420 收藏
-
409 收藏
-
157 收藏
-
307 收藏
-
395 收藏
-
270 收藏
-
494 收藏
-
393 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 485次学习