无法在SafeSubscriber._next读取未定义的属性“ push”

时间:2019-01-07 07:36:04

标签: angular typescript angular7

  

无法读取未定义的属性“ push”       在SafeSubscriber._next

import { Component, OnInit } from '@angular/core';
import {StudentService} from '../student.service';
import {student} from '../student';


@Component({
  selector: 'app-studentfrm',
  templateUrl: './studentfrm.component.html',
  styleUrls: ['./studentfrm.component.css'],
  providers:[StudentService]
})
export class StudentfrmComponent implements OnInit {


  students: student[];
  student: student;
    name: string;
  birthdate: string;
  gender: string;
  address: string;
  guardianname: string;
  contact: string;
  email: string;
  Areainterested: string;

  constructor(private studentservice: StudentService) { }

  addstudent()
  {
    const newstudent = {
      name: this.name,
      birthdate: this.birthdate,
      gender: this.gender,
      address: this.address,
      guardianname: this.guardianname,
      contact: this.contact,
      email: this.email,
      Areainterested: this. Areainterested
    }
    this.studentservice.addstudent(newstudent)
    .subscribe(student =>{
      this.students.push(student);
      // this.studentservice.getstudents()
      // .subscribe(students =>
      //   this.students = students);

    });
  }

我想将输入的数据发布到表单中。当我按此按钮时,出现此错误:

  

TypeError:无法读取未定义的属性“ push”       在SafeSubscriber._next(studentfrm.component.ts:42)       在SafeSubscriber.push ../ node_modules / rxjs / _esm5 / internal / Subscriber.js.SafeSubscriber .__ tryOrUnsub

3 个答案:

答案 0 :(得分:2)

只需初始化变量即可。

    ngOnInit() {
        this.students = [];
    }

答案 1 :(得分:0)

像波纹管一样定义

<pre>
students = new Array<student>();
</pre>

而不是像这样students: student[];

答案 2 :(得分:0)

您的student var未初始化。替换:

students: student[];

作者:

students: students[] = [];