javascript - 错误类型错误:无法读取未定义的属性“first_name”
问题描述
我收到此错误当我尝试将列表从后端服务呈现到视图时,能够获取响应数据并将其记录到控制台,但它不会呈现在视图上。
在此处输入代码
import { Component, OnInit, Input } from '@angular/core';
import { StudentsService } from '../services/students.service';
import { Student } from '../interfaces/Student';
@Component({
selector: 'app-student',
templateUrl: './student.component.html',
styleUrls: ['./student.component.css'],
})
export class StudentComponent implements OnInit {
@Input() student: Student;
students: Student[];
constructor(private studentService: StudentsService) {}
ngOnInit() {
this.studentService.getStudents().subscribe((students) => {
(data) => {
this.students = data.json();
Array.of(this.students);
};
console.log(students);
});
}
}
export interface Student {
id: number;
first_name: string;
last_name: string;
date_of_birth: Date;
}
<div class="container mt-5">
<ul *ngFor="let student of students">
<li>{{student.first_name}}</li>
</ul>
</div>
解决方案
(data) => {
this.students = data.json();
Array.of(this.students);
};
它不应该是一个函数。把它改成这样:
import { Component, OnInit, Input } from '@angular/core';
import { StudentsService } from '../services/students.service';
import { Student } from '../interfaces/Student';
@Component({
selector: 'app-student',
templateUrl: './student.component.html',
styleUrls: ['./student.component.css'],
})
export class StudentComponent implements OnInit {
@Input() student: Student;
students: Student[];
constructor(private studentService: StudentsService) {}
ngOnInit() {
this.studentService.getStudents().subscribe((students) => {
this.students = students; // students is response from server. if it is not Student[] you should map it to correct type.
});
}
}
推荐阅读
- salesforce-einstein - Einstein:图表字段顺序不同于 SAQL
- java - 由于 setOldSku(String oldSku) 已折旧
- python - 如何读取excel文件并将内容转换为python中的列表列表?
- php - 通过控制台显示从ajax中的字段获取的数据
- java - 自定义弹簧引导配置文件未在 IntelliJ 中激活
- reactjs - React - 如何找出 FireStore 集合中的最后一个文档
- java - 刷新面板时如何更改 JComboBox 中的选定索引?
- mysql - WRONG_VALUE_COUNT_ON_ROW:但我看不出问题?
- java - 当覆盖方法时,为什么必须先在超类中编写它,即使它对超类没有意义?
- javascript - 如何将变量 javascript 作为 html 中的样式 css 属性?