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

Angular服务中声明的属性未在视图更新的原因咨询

问题原因与解决办法

核心原因

GamePlayService中的temporaryRaise变量仅在类初始化时计算了一次初始值,后续调用raise()或raiseCpu()修改players[0].bettingAmount时,这个变量不会自动重新计算。

而模板中直接写{{this.gamePlay.players[0].bettingAmount+this.gamePlay.bigBlind}}时,Angular每次执行变更检测都会重新计算这个表达式,因此能实时展示最新结果。

解决办法

将temporaryRaise改为getter属性,确保每次访问它时都重新计算最新值:

修改GamePlayService代码:

export class GamePlayService {

  bigBlind: number = 20;
  
  players = [
    {name:'Cpu Player',chips:this.startingChips,isDealer:true,isBigBlind:false,isSmallBlind:false,isActivePlayer:false,bettingAmount:0,temporaryBetting:0},
    {name:'Me',chips:this.startingChips,isDealer:false,isBigBlind:false,isSmallBlind:false,isActivePlayer:true,bettingAmount:0,temporaryBetting:0},
  ];

  // 替换原有的temporaryRaise变量为getter
  get temporaryRaise(): number {
    return this.bigBlind + this.players[0].bettingAmount;
  }

  constructor() { }

  raise(ref:any){
    this.players[1].bettingAmount+=parseInt(ref);  
  }
}

这样模板中的{{this.gamePlay.temporaryRaise}}就能和直接计算的表达式一样,实时更新最新值了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 17:13:36