'Angular - Cannot read properties of undefined (reading 'forEach') by trying to manipulate variable after an HTTP call

I'm trying to manipulate a variable after an HTTP call. I want to use functions such as .push() or .forEach(), but it doesn't allow me because data isn't assigned to the variable at first.

I get an error in the console:

Cannot read properties of undefined (reading 'forEach')

My Component:

import {Component, OnInit} from '@angular/core';
import {TablesService} from "../tables.service";

@Component({...})

export class BigQueryComponent implements OnInit {
  fetchedData: any;
  DATA: any;

  constructor(private tableService: TablesService) {
    this.tableService.fetchAPI().subscribe((data) => {
      this.fetchedData = data;
    })
  }

  ngOnInit(): void {
    this.getQueryData();
  }

  getQueryData() {
    this.fetchedData.forEach( dataset => { 
      this.DATA.push( dataset );
    });
  }

}

My Service:

export class TablesService {

  constructor(private http: HttpClient) {}

  fetchAPI() {
    return this.http.get('https://.../products');
  }
}

How could I do this? I've tried to add Observable to the HTTP function, but I'm not sure how should it be done correctly.



Solution 1:[1]

Based on your requirement in the comment, you should move the logic from getQueryData to the subscribe function of fetchAPI. Thus, when the observable is returned, the fetchData will be assigned with data and proceed with the following logic.

And remove this.tableService.fetchAPI().subscribe code from constructor.

Normally we use ngOnInit() for initialization work as discussed in this question: Difference between Constructor and ngOnInit.

constructor(private tableService: TablesService) { }

getQueryData() {
  this.tableService.fetchAPI().subscribe((data) => {
    this.fetchedData = data;

    this.fetchedData.forEach( dataset => { 
      this.DATA.push( dataset );
    });  
  });
}  

Note:

Will suggest these two variables are defined with array type.

fetchedData: any[];
DATA: any[];

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1