Home > OS >  Cannot read properties of undefined (reading 'forEach') after trying to Manipulate variabl
Cannot read properties of undefined (reading 'forEach') after trying to Manipulate variabl

Time:10-28

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

I get 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 Observale to http function, but i'm not sure how should it be done correctly.

CodePudding user response:

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[];
  • Related