You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在NGRX Signal Store的withComputed中复用计算信号?

在NGRX Signal Store的withComputed中复用计算值的解决方案

你遇到的问题是因为withComputed回调接收的store参数仅包含初始state和之前已注册的信号/计算值,你在回调内刚定义的property1还未被合并到store实例中,所以无法通过store.property1()访问。

正确的做法是在回调内部先单独定义计算值变量,再直接复用这些变量创建后续计算值,最后统一返回:

export const ExampleStore = signalStore(
  withState(initialState),
  withComputed(store => {
    // 先单独定义计算值
    const property1 = computed(() => store.example());
    // 直接复用已定义的变量
    const property2 = computed(() => property1());
    
    return {
      property1,
      property2
    };
  })
);

这样写后,property2直接引用了已创建的property1信号,既能复用计算逻辑,最终返回的对象也会将两个计算值合并到store中,外部可以正常调用store.property1()和store.property2()。

内容的提问来源于stack exchange,提问作者Phong6698

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 08:09:50