0

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 ;/

Jacob Nelson
  • 2,370
  • 23
  • 35
  • 3
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – JSON Derulo Apr 10 '19 at 06:11
  • `console.log(this.osoby.length);` is giving an output `0`, which definitely means `this.osoby` don't have any value. Therefore, `this.osoby[1]` is definitely `undefined`. Please check if the API is returning any value. – Jacob Nelson Apr 10 '19 at 06:19

2 Answers2

1

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);
  });
Sachila Ranawaka
  • 39,756
  • 7
  • 56
  • 80
0

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);

  });
khvr000
  • 31
  • 1
  • 6