angular - Kan inte läsa egenskapen 'push' av undefined vid SafeSubscriber._next


Kan inte läsa egenskapen 'push' av undefined vid 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);

    });
  }

Jag vill skicka de data som jag fyller i mitt formulär. När jag trycker på det får jag detta fel:

TypeError: Kan inte läsa egenskapen 'push' av undefined vid SafeSubscriber._next (studentfrm.component.ts:42) vid SafeSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub

Svar #1

Initiera bara din variabel.

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

Svar #2

Din student-variabel är inte initialiserad. Ersätt:

students: student[];

av :

students: students[] = [];

Relaterade artiklar