【问题标题】:ERROR TypeError: Cannot read property 'first_name' of undefined错误类型错误:无法读取未定义的属性“first_name”
【发布时间】:2020-07-04 22:50:51
【问题描述】:

我收到此错误当我尝试从后端服务将列表呈现到视图时, 能够获取响应数据并将其记录到控制台,但它不会呈现在视图上。

在此处输入代码

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>

【问题讨论】:

    标签: javascript html angular typescript


    【解决方案1】:
       (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.
        });
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-04-29
      • 1970-01-01
      • 1970-01-01
      • 2021-07-20
      • 1970-01-01
      • 2021-12-03
      • 2021-11-22
      • 2018-07-12
      • 2021-12-16
      相关资源
      最近更新 更多