
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”开头的多个功能,但它们只能访问之前定义的功能。
使用对于大型企业应用程序来说,商店可能会变得复杂且难以管理。在为项目编写功能和组件时,拆分得越好、越细,就越容易管理、维护代码和为其编写测试。
但是,考虑到 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(),
);
注入signalstore
深度信号
目前我认为这是对默认 signal api 的一个很好的补充,使其成为管理的一个不错的选择:
https://www.angulararchitects.io/blog/the-new-ngrx-signal-store-for-angular-2-1-flavors/(关于该主题的 4 篇文章)
https://ngrx.io/guide/signals
以上就是NGRX 的信号存储 - 主要概念细分的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号