0

I am trying to get data from api to array with .subscribe but the array will stay empty

dataService.ts

 getData(): Observable<Data[]> {
        return this.http.get<Data[]>(this.dataUrl);       
      }

data.ts

 data: Data[] = [];
  

  ngOnInit(): void {
    this.getData();
    console.log(this.data[0].dataId);
  }


  getData(): void {
    this.dataService.getData()
        .subscribe(data => this.data = data)

  }

1 Answers1

2

Your code is getData function is async, you should console log in your subscriber

getData(): void {
    this.dataService.getData().subscribe(data => {
      this.data = data;
      console.log(this.data[0].dataId);
    })
}

Your ngOnInit is sync code, so, when it run through getData function call which is an async function, it will not wait. Therefore, the data is not loaded yet, undefined.