Remigiusz 1998
Remigiusz 1998

Reputation: 11

Why undefined is displayed instead of object - (Angular HTTP request)

I want to get an array from Spring Boot API and I can't convert data into object properly

It's my model:

export class Uczen {

  constructor(
    public firstname: string,
    public lastname: string,
    public email: string,
    public gender: string,

  ) {  }

}

service:

getPersons() {
    return this.http.get('http://localhost:8080/myApp/persons');
}

It's my component.ts code

  osoby: Uczen[] = [];

ngOnInit() {
  this.personService.getPersons().subscribe((result: Uczen[]) => {
        for (const item of result) {
        this.osoby.push(item);
      }
  });
  console.log(this.osoby[1]);
  console.log(this.osoby.length);
}

im getting "undefined" and "0" as display,there is problem with conversion json to object array prodably ;/

Upvotes: 0

Views: 678

Answers (2)

khvr000
khvr000

Reputation: 31

In your ts file, you have ngOnInit() method, ngOnInit is component's life cycle hook which runs when component is being initialized.

1) Initially the control calls the getPersons() method and it will take some time (some milli seconds) to get response from your server.

2)Due to asynchronous behaviour, before we get response from remote server the control goes to the console statement line and it is executed. At this point of time the variable osoby is still an empty array, which is why you are getting undefined , accessing first element of empty array.

3)If you write the same console lines inside subscription, the control to those lines will go only after receiving the response from your server .

  this.personService.getPersons().subscribe((result: Uczen[]) => {
    for (const item of result) {
      this.osoby.push(item);
    }

   console.log(this.osoby[1]);
   console.log(this.osoby.length);

  });

Upvotes: 0

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41387

consoles should be inside the subscription since this is an asynchronous procedure

  this.personService.getPersons().subscribe((result: Uczen[]) => {
        for (const item of result) {
          this.osoby.push(item);
        }

       console.log(this.osoby[1]);
       console.log(this.osoby.length);
  });

Upvotes: 1

Related Questions