Angular 5.1.0模板绑定传递类实例调用方法时出现x is not a function错误
嘿,我之前开发Angular Quiz应用时也碰到过一模一样的问题!咱们一步步拆解这个“x is not a function”的坑,顺便实现你要的高亮功能。
最常见的原因:数据序列化丢失了类方法
你大概率是直接把API返回的JSON数据当成了Question类的实例来用——但JSON转成的只是普通JavaScript对象,根本没有isAnsweredCorrectly()方法!模板里调用自然会报错。
解决办法:把JSON映射成真正的Question实例
首先给你的Question类加一个静态工厂方法,专门用来把JSON数据转换成类实例:
// question.model.ts export class Question { id: number; text: string; options: string[]; correctAnswer: string; userAnswer?: string; constructor(data: Partial<Question>) { Object.assign(this, data); } isAnsweredCorrectly(): boolean { return this.userAnswer === this.correctAnswer; } // 关键:把JSON转成Question实例的工厂方法 static fromJson(data: any): Question { return new Question(data); } }
然后在获取数据的服务里,用这个方法把每一条JSON数据都转成实例:
// question.service.ts getQuestions(): Observable<Question[]> { return this.http.get('/api/questions').pipe( map((response: any[]) => response.map(item => Question.fromJson(item))) ); }
验证是否解决:检查实例类型
在组件里加个控制台输出,确认你的questions数组里的元素真的是Question实例:
ngOnInit() { this.questionService.getQuestions().subscribe(questions => { this.questions = questions; console.log(this.questions[0] instanceof Question); // 应该返回true }); }
如果返回false,说明还是没转成实例,再检查一下数据处理的逻辑。
避免模板绑定的坑
别在*ngFor里解构对象,否则会丢失实例方法:
<!-- ❌ 错误:解构后变成普通对象,丢了方法 --> <div *ngFor="let { id, text } of questions">...</div> <!-- ✅ 正确:直接使用完整的Question实例 --> <div *ngFor="let question of questions">...</div>
实现高亮功能
现在实例没问题了,直接在question-list组件的模板里用类绑定来实现高亮:
<!-- question-list.component.html --> <ul class="question-list"> <li *ngFor="let question of questions" [class.highlight-correct]="question.isAnsweredCorrectly()" [class.highlight-incorrect]="question.userAnswer && !question.isAnsweredCorrectly()"> {{ question.text }} <!-- 其他问题内容,比如选项、用户答案 --> </li> </ul>
对应的CSS样式:
/* question-list.component.css */ .highlight-correct { background-color: #d4edda; border-left: 4px solid #28a745; padding-left: 10px; } .highlight-incorrect { background-color: #f8d7da; border-left: 4px solid #dc3545; padding-left: 10px; }
额外提醒:别覆盖实例
更新用户答案的时候,直接修改实例的属性,不要把整个元素替换成普通对象:
// ❌ 错误:替换成普通对象,丢失方法 this.questions[index] = { ...this.questions[index], userAnswer: selectedAnswer }; // ✅ 正确:直接更新实例属性,保留方法 this.questions[index].userAnswer = selectedAnswer;
内容的提问来源于stack exchange,提问作者Dmytro
相关产品推荐
相关产品推荐

