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

2
  • 3
    Possible duplicate of How do I return the response from an asynchronous call? Commented Apr 10, 2019 at 6: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. Commented Apr 10, 2019 at 6:19

2 Answers 2

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);
  });
Sign up to request clarification or add additional context in comments.

Comments

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

  });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.