0

Using http.get().subscribe the data returns as a empty array, however if I call a console.log() inside the subscribe code the array shows correctly.

This is the code:

  public data: Noticia[] = [];
  public api = "http://localhost:3000/data"

  constructor(
    private httpClient: HttpClient
    ) { }

  ngOnInit() { 
        this.httpClient.get(this.api).subscribe((response: Noticia[]) =>{
        response.forEach(news =>{
          this.data.push(news);
        });
       
        console.log("data in subscribe", this.data);
      });
      console.log("data",this.data);
      console.log("data [0]",this.data[0]);
  }

This is the console logs:

enter image description here

How can I keep the data after the subscribe is over?

1 Answers1

-1

It is very normal because these 2 lines are outside the subscribe().

console.log("data",this.data);

console.log("data [0]",this.data[0]);

According to your code, the array "data" will be logged before it is filled.

As soon as the observable get resolved in the subscribe method, then you will have the data available.

In this case, you need just to move the two lines in the next callback (in the subscribe method) to have this code

ngOnInit() { 
     this.httpClient.get(this.api).subscribe((response: Noticia[]) =>{
     response.forEach(news =>{
         this.data.push(news);
      });
       
      console.log("data in subscribe", this.data);
      console.log("data",this.data);
      console.log("data [0]",this.data[0]);
    });
  }
Amine Safi
  • 255
  • 4
  • 8