特征
- 基于信号
- 函数式和声明式
- 用于本地或全局状态管理
- 可通过自定义功能进行扩展
与 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));
},
})),
</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 ) => {
return products.filter(p => p.category === category);
},
})),
);
}
</product>
现在是 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