PHP前端开发

NGRX 的信号存储 - 主要概念细分

百变鹏仔 3天前 #JavaScript
文章标签 信号

特征

与 ngrx 全球商店相比如何?

ngrx signal store 的创建者,marko stanimirovic 在这里描述了 ngrx signalstore:深入了解 angular 中基于信号的状态管理

基于类的状态管理限制:

让我们通过代码示例来探索商店的 api。我们将使用一个包含产品列表和过滤功能的项目。

创建一个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 挂钩

import { withhooks } from "@ngrx/signals"; export const productstore = signalstore( withhooks((store) => ({   oninit() {     // load products when the store is initialized     store.loadproducts();   }, })),);
使用实体

管理集合

export const productstorewithentities = signalstore( withentities<product>(), // crud operations withmethods((store,   productservice = inject(productservice), ) =&gt; ({   loadproducts: () =&gt; {     const products = tosignal(productservice.loadproducts())();     patchstate(store, setallentities(products || []));   },   updateproduct: (product: product) =&gt; {     productservice.updateproduct(product);     patchstate(store, setentity(product));   }, })),</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(() =&gt; ({   getproductsbetweenpricerange: (lowprice: number, highprice: number, products: array<product>, ) =&gt; {     return products.filter(p =&gt; p.price &gt;= lowprice &amp;&amp; p.price ) =&gt; {     return products.filter(p =&gt; p.category === category);   }, })), );}</product>
现在是

signalstorefeature 的示例,它展示了跨多个商店重用 signalstorefeature 的可能性。

从“@ngrx/signals”导入{ patchstate, signalstorefeature, withmethods };


export function withCrudOperations() { return signalStoreFeature(   withMethods((store) =&gt; ({     load: (crudService: CrudOperations) =&gt; crudService.load(),     update: (crudableObject: CRUD, crudService: CrudOperations) =&gt; {       crudService.update(crudableObject);       patchState(store, setEntity(crudableObject));     },   }), ));}export interface CrudOperations { load(): void; update(crudableObject: CRUD): void;}// Product &amp; 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 storesexport const ProductStore = signalStore( withCrudOperations(),);export const CustomerStore = signalStore( withCrudOperations(),);
ngrx 工具包实用程序包

由于易于扩展,已经有一个名为 ngrx-toolkit 的实用程序包,旨在向信号存储添加有用的工具。

注入signalstore

{providedin: ‘root’} 或在组件、服务、指令等的提供者数组中

深度信号

补丁状态

接收方法

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