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

Angular猫咪投票应用点击后票数无法递增问题求助

问题分析与解决方案

核心问题

你的代码里voteForThisCat()方法仅完成了随机切换猫咪的逻辑,完全未执行票数递增操作;同时初始返回的猫咪数据中没有rating字段,导致无法正确初始化票数。

修复步骤

1. 补全票数递增逻辑

修改voteForThisCat()方法,找到对应猫咪后更新其rating值:

voteForThisCat(id: string) {
  const likedCatIndex = this.allcats.findIndex((cat: Cat) => cat.id === id);
  if (likedCatIndex !== -1) {
    // 更新该猫咪的票数
    this.allcats[likedCatIndex].rating = this.getIncrementedCatRatingValue(this.allcats[likedCatIndex].rating);
  }
  // 切换到新的随机猫咪
  this.twoCatsArray = this.chooseTwoRandomCats(this.allcats);
}

2. 初始化猫咪的rating字段

返回的JSON数据中所有猫咪都没有rating属性,需在获取数据时为每只猫咪初始化票数:

showMeTwoCats() {
  this.catService.getAllCat().subscribe((cats: CatList) => {
    // 为每只猫咪添加初始rating=0
    this.allcats = cats.images.map(cat => ({ ...cat, rating: 0 }));
    this.twoCatsArray = this.chooseTwoRandomCats(this.allcats);
  });
}

3. 可选:显示当前票数

如果需要在页面展示票数,修改HTML模板:

<div class="cat" *ngFor="let cat of twoCatsArray" (click)="voteForThisCat(cat.id)">
    <img class="cat-image" [src]="cat.url">
    <p>票数: {{ cat.rating }}</p>
</div>

失效原因说明

  • voteForThisCat()仅执行了findIndex查找猫咪,未对找到的猫咪做任何票数更新操作
  • 初始数据无rating字段,调用getIncrementedCatRatingValue后未将返回值赋值给猫咪对象
  • 未修改猫咪属性,Angular变更检测不会触发视图更新

内容的提问来源于stack exchange,提问作者Cyndélia Guillaume

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 07:35:24