InvalidAction: The function forEach cannot be applied to "res"

Here is the HTML code that I am currently working with:

<div *ngIf="chart" class="col-xl-4 col-lg-6">
      <div class="card cardColor mb-3">
        <div class="card-header headColor">
          <img class="img-fluid" src="../../../assets/images/chart-bars-box-16-white.png" /> &nbsp;
          <b>Issue Chart</b>
        </div>
        <div class="card-body">
          <canvas id="canvas">{{ chart }}</canvas>
        </div>
      </div>
    </div>  

I am using an API to fetch data from this URL:

url = 'https://api.myjson.com/bins/1dnpid';  

The following code snippet is for creating a line graph:

// line graph
        this.httpClient.get(this.url).subscribe((res: Data[]) => {
            res.forEach(y => {
              this.year.push(y.year);
              this.price.push(y.price);
            });
            this.chart = new Chart('canvas', {
              type: 'line',
              data: {
                labels: this.year,
                datasets: [
                  {
                    data: this.price,
                    borderColor: '#6ea204',
                    fill: false
                  }
                ]
              },
              options: {
                legend: {
                  display: false
                },
                scales: {
                  xAxes: [{
                    display: true
                  }],
                  yAxes: [{
                    display: true
                  }],
                }
              }
            });
          });  

In order to manage the data, I have created the following interface:

export interface Data {
    year: String;
    price: number;
}

When running this code in a browser, I encounter the following error message:

ERROR TypeError: res.forEach is not a function
  at SafeSubscriber._next (dashboard.component.ts:130)

What could be causing this issue?

Answer №1

According to @Félix, objects do not inherently have a foreach method. However, you can iterate over an object if it is iterable or Array-like by using the following approach:

Array.from(res).forEach

Answer №2

This error occurs when attempting to use the foreach method on objects, as they do not have this functionality. Arrays are the proper data structure for iterating over elements.

If your API response contains an object with a key called results, it likely holds the array you need to loop through.

To properly iterate over this array, make sure to use res.results.forEach.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Neither of the elements within the ngIf statement is visible despite the fact that one of them should evaluate to true

I'm currently grappling with using ngIf to conceal a component's details until the necessary variable is set. During this waiting period, it should display a loading message. Despite my efforts to find a solution through online searches, I'v ...

The ng lint command is successful, yet an error appears in VS Code

I'm currently utilizing the tslint tool in my Angular project. Here is an excerpt from my tsconfig.json file: { "compileOnSave": false, "compilerOptions": { "downlevelIteration": true, "impor ...

Anticipating the arrival of an external JavaScript file in the child component

I am facing an issue with my parent component that dynamically loads an external js file (similar to what is explained here). The child component needs a variable inside the js file, but it throws an error every time the page is loaded because the child c ...

Using JQuery and CSS to handle multiple hyperlink links with a single action

UPDATE: Issue resolved, thanks for the help. It is working fine now: http://jsfiddle.net/c3AeN/1/ by Sudharsan I have multiple links on my webpage, all in a similar format like this: note: When I say 'similar format', I mean that all links share ...

Guide to retrieving a user's current address in JSON format using Google API Key integrated into a CDN link

Setting the user's current location on my website has been a challenge. Using Java Script to obtain the geographical coordinates (longitude and latitude) was successful, but converting them into an address format proved tricky. My solution involved le ...

AngularJS blank drop-down selection

I am currently working on an AngularJS select element with ng-options using the code below: <select ng-model="vm.selectedship" ng-change="vm.updateShip()" data-ng-options="ship as ('ship' + ' is ready (' + ship.currentlocation + & ...

What is the best way to retrieve the browser language using node.js (specifically express.js)?

element, consider the scenario where a user requests a specific page and you are interested in determining the language set in their browser on the server side. This information is crucial as it enables you to customize the template with appropriate messa ...

What is the most efficient way to execute useEffect when only one specific dependency changes among multiple dependencies?

My main objective is to update a state array only when a specific state (loadingStatus) undergoes a change. Yet, if I include solely loadingStatus as a dependency, React throws an error requesting all dependencies [loadingStatus, message, messageArray, set ...

Typescript validation of tokens using Azure functions

Currently working on a website utilizing Azure Static Web App, where the login/registration is managed by Azure B2C. The backend API consists of typescript Azure functions integrated with Azure Static web app. Certain API calls can only be accessed when th ...

Element on webpage "Expands" When Scrolled into Visibility

After posting a question on Stack Overflow, I noticed discrepancies between the element dimensions reported by Chrome Inspector and Selenium WebDriver. While Chrome Inspector showed w = 979, h = 1961, Selenium returned dimensions of 979 and 1461 respective ...

Show User-Specific Information Using DataTable

After conducting extensive research, I have been unable to find a suitable example to reference. My goal is to customize my DataTable so that it only displays data relevant to the currently logged-in user (admin accounts will have access to all data). I am ...

What is the method for launching a new tab within an incognito window that is already open?

In the process of developing a Chrome extension, I am focusing on the functionality of creating a new tab from context menus within an incognito window. My current approach involves using the following script: chrome.windows.create({url: "https://google.c ...

Angular 10 introduces a new approach to handling concurrency called "forkJoin"

Here is the code I have: async getBranchDetails() ----component method { let banks = this.bankDataService.getBanks(); let branchTypes = this.branchDataService.getBranchTypes(); forkJoin([banks,branchTypes]).subscribe(results => { ...

Creating repeatable texture patterns in Three.js

Hello, I have developed a basic renderer for my 3D objects that are generated using PHP. While I am able to successfully render all the objects, I am facing some major issues with textures. Currently, the texture I am using is sized at 512x512 pixels. I ...

Javascript code creates a blur effect on webpage bodies

On my webpage, I have multiple elements, including a "change BG" button. When this button is clicked, I want to hide all other content on the page except for the button using JavaScript. Alternatively, clicking the button could blur out all other elements ...

What is the best way to store multiple forms in a single request using React?

Is there a more efficient way for me to save multiple forms in multiple child components from the parent component using just one API request? I have attempted to utilize Context and reducer, which did work. However, I am unsure if this is the best approa ...

The duration required to render DOM elements

Trying to determine the best method for measuring the rendering time of DOM elements in a web browser. Any tips? I'm currently developing an application that involves significant DOM manipulation as part of comparing the performance between Angular 1 ...

Only display PHP page content if accessed through an AJAX request, not through directly typing the URL into the address bar

Is there a way to verify if a PHP page has been accessed via an Ajax request? I'm working on a page that displays a form for updating some database data (update.php), but I only want it to be accessible if it is called by a specific page named "change ...

Need some assistance with Javascript Ajax? Specifically, dealing with multiple values?

My goal is to asynchronously post an array of messages using this code. Despite my efforts, I've encountered a challenge where it doesn't only post the four items in the array but also adds gibberish text. Additionally, there seems to be an issue ...

Failed to load CSS file in nodeJS application

I followed a tutorial to create a backend app using nodeJS and Express. My MongoDB connection with Mongoose is working fine. However, I am facing issues when trying to add a simple front-end using html/ejs/css. The endpoints are loading on localhost but on ...