-1

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.

Yong Shun
  • 35,286
  • 4
  • 24
  • 46
  • 2
    And what is the value of `fetchedData` _before_ the call completes? Either you need a sensible default value, or you should use observables with e.g. the async pipe to handle the data. – jonrsharpe Oct 27 '21 at 08:21
  • data is undefined at first. I want to fetch data from API and after it's fetched I want to manipulate it. Not sure how observables with async pipe works, but ill take a look into that. Thanks. – Rihards Ādminis Oct 27 '21 at 08:29

1 Answers1

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[];
Yong Shun
  • 35,286
  • 4
  • 24
  • 46