0

I don't understand why the object "student" is undefined in the context below when I try to, based on it, access a variable of that object (a list of other objects). What I mean is this:

In the code below there are "student" and "courses" objects. The "student" object has the attribute "courses" which is of "Courses[]" type. I want to, based on that "student" object's "courses" attribute, populate the "courses" object inside of the class. I hope I'm clear on what I mean.

My question: Why is the "student" object reported as "undefined", even though based on it, I'm populating the contents of the .html component of that page?

import { Component, OnInit, Input } from '@angular/core';
import { Student } from '../student';
import { Course } from '../course';
import { ActivatedRoute } from '@angular/router';
import { Location } from '@angular/common';

import { StudentsService }  from '../students.service';

@Component({
  selector: 'app-student-detail',
  templateUrl: './student-detail.component.html',
  styleUrls: ['./student-detail.component.css']
})
export class StudentDetailComponent implements OnInit {

  @Input() student: Student;
  courses: Course[];

  constructor(
    private route: ActivatedRoute,
    private studentsService: StudentsService,
    private location: Location
  ) {}

  private jmbagId: string;

  ngOnInit(): void {
    this.getStudent();
  }

  getStudent(): void {
    this.jmbagId = this.route.snapshot.paramMap.get('jmbag');
    this.studentsService.getStudent(this.jmbagId)
      .subscribe(student => this.student = student);
    console.log(this.student);
  }

}

Working HTML

<li *ngFor="let course of student.courses">

What I'm wondering why isn't it working about HTML

<li *ngFor="let course of courses">
Gandeloft
  • 45
  • 8
  • 1
    Does this answer your question? [How do I return the response from an Observable/http/async call in angular?](https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular) – Krypt1 May 08 '20 at 12:04
  • If you are asking why ```this.student``` console undefined then put your ```console.log(this.student)``` inside subscribe and it will work. – Dipak Telangre May 08 '20 at 12:05

1 Answers1

1
this.studentsService.getStudent(this.jmbagId)
  .subscribe(student => this.student = student);
console.log(this.student);

It is async so this.student will be undefined at first

Alexander
  • 3,019
  • 1
  • 20
  • 24