NGRX Signal Store 的创建者,Marko Stanimirovic 在此描述了 NgRx SignalStore:深入了解 Angular 中基于信号的状态管理
让我们通过代码示例探索商店的 API。我们将使用一个包含产品列表和过滤功能的项目。
import { signalStore } from "@ngrx/signals"; export const ProductStore = signalStore( … );
与迄今为止的任何 NGRX Store 一样,可以使用函数 withState 来提供初始状态,该函数接受对象文字、记录或工厂函数(用于创建动态初始状态)作为输入。
import { signalStore, withState } from "@ngrx/signals"; const initialProductState: ProductState = { products: [] }; export const ProductStore = signalStore( withState(initialProductState); );
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 获取工厂函数并返回可以通过使用访问的方法和计算信号的字典商店。它们还在注入上下文中运行,这使得可以将依赖项注入到它们中。
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), ) => ({ loadProducts: () => { const products = toSignal(productService.loadProducts())(); patchState(store, setAllEntities(products || [])); }, updateProduct: (product: Product) => { productService.updateProduct(product); patchState(store, setEntity(product)); }, })),
可以添加以“with”开头的多个功能,但它们只能访问之前定义的内容。
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-toolkit 的实用程序包,旨在向信号存储添加有用的工具。
{providedIn: ‘root’} 或在组件、服务、指令等的提供者数组中
对于大型应用程序来说,它的可靠性还有待证明,尤其是作为全球商店应用时。
目前我认为这是对默认 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 的信号存储 - 主要概念细分的详细内容。更多信息请关注PHP中文网其他相关文章!