【发布时间】:2021-07-11 16:34:36
【问题描述】:
我创建了一个 Angular 类 Course,它有另一个 Angular 类 Student,作为它的属性之一。每个类的对象都是从我的后端应用程序中以 RESTfully 方式提供的(工作正常,经过邮递员测试)。我试图在我的模板中显示一个列出每个课程和学生的表格;但是,浏览器会出现以下错误:'Student | undefined' 不可分配给类型 'NgIterable |空 |未定义'。
代码如下:
课程.ts
import { Student } from './student';
export class Course {
id?: number;
name?: string;
department?: string;
student?: Student
}
学生.ts
export class Student {
id?: number;
name?: string;
email?: string;
dob?: Date;
age?: number;
}
课程列表.component.ts
import { Component, OnInit } from '@angular/core';
import { Course } from '../course';
import { CourseService } from '../course.service';
@Component({
selector: 'app-course-list',
templateUrl: './course-list.component.html',
styleUrls: ['./course-list.component.css']
})
export class CourseListComponent implements OnInit {
courses?: Course[];
constructor(private courseService: CourseService) { }
ngOnInit(): void {
this.getCourses();
}
private getCourses() {
this.courseService.getCourseList().subscribe(data => {
this.courses = data;
console.log("Course List", this.courses);
});
}
}
来自getCourses() 的console.log("Course List", this.courses); 显示了我期望的JSON 对象(示例):
0:
department: "FACS"
id: 401
instructor: null
name: "Underwater Basket Weaving"
student:
age: 43
dob: "23 JAN 1977"
email: "arrowGuy77@nevermisses.net"
id: 103
name: "Hawk Eye"
course.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Course } from './course';
@Injectable({
providedIn: 'root'
})
export class CourseService {
private baseURL = "http://localhost:8082/api/v1/courses";
constructor(private httpClient: HttpClient) { }
getCourseList(): Observable<Course[]> {
return this.httpClient.get<Course[]>(this.baseURL);
}
}
课程列表.component.html
<h2>Course List</h2>
<table class = "table table-striped">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Department</th>
</tr>
</thead>
<tbody>
<tr *ngFor = "let course of courses">
<td>{{course.id}}</td>
<td>{{course.name}}</td>
<td>{{course.department}}</td>
<td *ngFor = "let student of course.student">
<p>{{student.name}}</p>
</td>
</tr>
</tbody>
</table>
第二个 *ngFor 是问题。
【问题讨论】:
标签: json angular typescript