使用ngx-snake获取积分数据失败:无法拿到积分却显示游戏网格
解决ngx-snake积分收集与重复网格问题
问题分析
foodEaten事件不传递积分参数:官方文档仅说明该事件在蛇吃食物时触发,未提及返回积分值,你之前通过$event获取points的方式无效,导致控制台输出异常。- 重复游戏网格:大概率是组件渲染异常或模板中存在重复渲染逻辑。
解决步骤
1. 正确获取积分数据
ngx-snake组件通常会暴露当前积分的属性(如score),需通过@ViewChild获取组件实例后读取:
组件类代码
import { Component, ViewChild } from '@angular/core'; import { NgxSnakeComponent } from 'ngx-snake'; @Component({ selector: 'app-your-component', templateUrl: './your-component.component.html', styleUrls: ['./your-component.component.css'] }) export class YourComponent { // 获取snake组件实例 @ViewChild(NgxSnakeComponent) snakeComp!: NgxSnakeComponent; totalPoints = 0; // 自定义累加积分变量 onFoodEaten(): void { // 读取组件当前积分 const currentScore = this.snakeComp.score; this.totalPoints += currentScore; console.log('当前积分:', currentScore, '累计积分:', this.totalPoints); } }
模板代码
<div class="container-user"> <ngx-snake (foodEaten)="onFoodEaten()"></ngx-snake> </div>
2. 消除重复游戏网格
- 检查模板文件,确保仅存在一个
<ngx-snake>标签; - 排查组件CSS,确认
.container-user或父容器未设置导致组件重复渲染的样式(如display: contents或意外的循环渲染); - 核对模块声明,确保
NgxSnakeModule仅在根模块或当前组件所属模块中导入一次,避免重复注册。
额外注意
若上述方法无效,检查ngx-snake的版本是否与文档匹配,部分旧版本可能未暴露score属性,需升级到对应版本或查看版本适配的文档说明。
内容的提问来源于stack exchange,提问作者Runner
相关产品推荐
相关产品推荐

