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

Angular组件赋值时出现只读属性错误的技术问题

解决“x是只读属性”的错误问题

嘿,我一眼就发现问题所在啦——你定义的value是个只读的getter属性,它只有获取计算结果的逻辑,没有提供设置值的方法,所以当你在submit()里尝试给this.value赋值时,TypeScript就会抛出“只读属性”的错误。

结合你的需求(把复选框的求和结果存到details.x),这里有两种简单的解决方式:

方案一:直接给details.x赋值(最直接)

既然value的作用是计算求和结果,那你不需要给value赋值,直接把计算出来的this.value存到details.x就好:

export class AppComponent { 
  details:{a: boolean, b:boolean, c:boolean, x:number} = { a: false, b: false, c: false, x: 0, }; 
  public get value(): number { 
    const numbermap = { a: 1, b: 2, c: 3 } //value of checkboxes; 
    return Object.entries(this.details) 
      // get only the entries with true value 
      .filter(([_key, value]) => value) 
      // map the keys having true to an array of numbers 
      .map(([key]) => numbermap[key]) 
      // requred for preventing error from reduce if none selected `[].reduce()` 
      .concat(0) 
      // sum the numbers with reduce 
      .reduce((prev = 0, curr) => prev + curr) 
  } 
  submit() { 
    // 直接把求和结果赋值给details.x
    this.details.x = this.value; 
    console.log(this.details.x); // 此时输出的就是求和后的值
  } 
}

这个方案最贴合你的需求,因为value本质是一个计算属性,不需要承担存储值的职责,直接操作details.x更清晰。

方案二:给value添加setter(适合需要双向绑定的场景)

如果你的业务逻辑里需要通过value来统一处理赋值逻辑(比如在模板里双向绑定[(value)]),那可以给value添加一个setter,让赋值操作同步到details.x:

export class AppComponent { 
  details:{a: boolean, b:boolean, c:boolean, x:number} = { a: false, b: false, c: false, x: 0, }; 
  public get value(): number { 
    const numbermap = { a: 1, b: 2, c: 3 } //value of checkboxes; 
    return Object.entries(this.details) 
      .filter(([_key, value]) => value) 
      .map(([key]) => numbermap[key]) 
      .concat(0) 
      .reduce((prev = 0, curr) => prev + curr) 
  } 
  // 新增setter,将赋值的内容同步到details.x
  public set value(newValue: number) {
    this.details.x = newValue;
  }
  submit() { 
    // 现在可以正常给value赋值了,赋值后details.x会被同步更新
    this.value = this.value; // 这里把求和结果赋值给value,同步到details.x
    console.log(this.details.x); 
  } 
}

小提醒

看你原来的submit()代码写的是this.value = this.details.x,这其实是把details.x的旧值赋给value,和你“把求和结果存到x”的需求刚好相反哦,记得改成对应方案里的正确写法~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:33:36