【问题标题】:Using *ngFor to display Angular 12 class inside a class使用 *ngFor 在类中显示 Angular 12 类
【发布时间】: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


    【解决方案1】:

    课程中的学生属性,而不是列表,因此要解决此错误,您需要更改

    <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>
    

    成为

    <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>
                    <p>{{course.student.name}}</p>
                </td>
            </tr>
        </tbody>
    </table>
    

    【讨论】:

      【解决方案2】:

      Course.student 不是一个数组,它是一个对象,但您正试图将它放在一个 ngFor 中(这是应该遍历列表/数组的东西)。

      如果您只想显示名称,您可以这样做:

      <tr *ngFor = "let course of courses">
        <td>{{course.id}}</td>
        <td>{{course.name}}</td>
        <td>{{course.department}}</td>
        <td>{{course?.student?.name}}</td>
      </tr>
      

      ?. 运算符确保在 course.student 未定义时不会引发错误。

      【讨论】:

        【解决方案3】:

        请说明一件事:

        • 您是否有可能拥有多名学生?

        • 每门课程可能只有一名学生?

        多个学生 - 您必须拥有student?: Studentstudents?: Student[] 的属性 所以这个结构

        0:
           department: "FACS"
           id: 401
           student:
              age: 43
              name: "Hawk Eye"
        

        你应该重做

        0:
           department: "FACS"
           id: 401
           students: [
              {
              age: 43
              name: "Hawk Eye"
              },
              {
              age: 33
              name: "Other guy"
              },
              ...
        

        这你需要用&lt;td *ngFor = "let student of course.students"&gt;迭代学生

        接下来,如果每门课程只有一名学生,则根本不必使用 *ngFor。 对于每个课程迭代,只需使用第一个 *ngFor 构造 &lt;tr *ngFor = "let course of courses"&gt; 呈现 course.student 名称和其他信息。

        <tr *ngFor = "let course of courses">
                    <td>{{course.id}}</td>
                    <td>{{course.name}}</td>
                    <td>{{course.department}}</td>
                    <td>
                        <p>{{course.student.name}}</p>
                        <p>{{course.student.age}}</p>
                        <p>{{course.student.email}}</p>
                    </td>
                </tr>
        

        【讨论】:

          猜你喜欢
          • 2019-10-08
          • 2021-05-24
          • 1970-01-01
          • 1970-01-01
          • 2019-05-02
          • 2023-03-13
          • 2018-05-16
          • 2022-10-05
          • 1970-01-01
          相关资源
          最近更新 更多