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

Is it possible to set up multiple registries within a single package.json configuration?

Is it possible to define two different registries within the publishConfig section of the package.json file? The scenario is that we want to publish the artifact to two different locations depending on its purpose. For SNAPSHOT versions, we would like to ...

Activate PHP using javascript

My PHP script is designed to capture a user's IP address, current webpage, screen resolution, and Date/Time when they visit my website. To implement this tracking functionality on another website, I plan to insert the following line of code: <scr ...

"Encountering a net::ERR_UNKNOWN_URL_SCHEME error message when making an Ajax post request

I'm encountering an issue while attempting to make a post call using Ajax from my frontend to my Express server. The error message I'm getting is net::ERR_UNKNOWN_URL_SCHEME. Here's the code snippet for the Ajax request: function sendStep ...

It appears that the Angular 2 HTTP header is being produced or transmitted erroneously

Trying to send a request to my backend that uses HTTP Basic authentication for testing purposes. username: user password: password The correct header should be: Authorization: Basic dXNlcjpwYXNzd29yZA== Request tested with this header in Chrome Advance ...

Ways to prompt a specific text value to generate varied responses

Whenever I try to input the letter "h", I expect a specific value in return but for some reason, it's not working as intended. Despite my best efforts to troubleshoot the issue, I have been unsuccessful in finding a solution. It's frustrating bec ...

Handling the same form button repeatedly in a loop using jQuery

I have successfully set up jquery to accept form data and send it to flask, but I am facing two issues: It only accepts the first form, which has the same IDs repeated for each element. I want all forms to be able to submit. When a submission occurs, it ...

Displaying data on View is not working after navigation

I'm facing an issue where the data is not displaying on the view after routing, even though it appears in the console. Surprisingly, if I don't change the view, the data shows up. Additionally, if I call the service directly from the view, I can ...

Is there a way to filter an array of dates without using the map function when a click

After finally grasping how to pass and retrieve data in React, I encountered an issue. I have a click handler called this.SortASC, and when I click on the title, I want to sort the titles alphabetically. However, I'm having trouble getting this functi ...

Is there a way to allow users to edit all the input fields within the td elements when they click the edit button for a specific row?

I am completely new to web dev and I'm struggling with what should be a simple task. My goal is to enable editing of all inputs in a table row when the edit link is clicked. Since I am not using jQuery, I prefer a pure JavaScript solution if possible. ...

What is the method for sending a Post request using the "content type" value of "application/x-www-form-urlencoded"?

Need to send a request to the oAuth2 authentication server to obtain a token. The request works fine in postman but encountering issues when trying to make the same request from Angular 4. CORS configuration is correct as other requests are functioning p ...

Please come back after signing up. The type 'Subscription' is lacking the specified attributes

Requesting response data from an Angular service: books: BookModel[] = []; constructor(private bookService: BookService) { } ngOnInit() { this.books = this.fetchBooks(); } fetchBooks(): BookModel[] { return this.bookService.getByCategoryId(1).s ...

Duplicating a concealed div and transferring it to a new div

I'm encountering an issue while trying to copy one div to another. The div I'm attempting to copy has a hidden parent div. The problem is that the destination div does not appear after copying, even though I changed its style display to block. ...

React Native: struggling to fetch the most up-to-date information from an array

I'm working on a chat application that functions similar to a chatbot. Since I don't want to use a database and the messages are temporary, I opted to utilize JavaScript arrays. Whenever a user inputs a message in the TextInput and hits the butto ...

Addressing the issue of empty ngRepeat loops

Utilizing ngRepeat to generate table rows: <tr ng-repeat="User in ReportModel.report" on-finish-render> <td><span>{{User.name}}</span></td> </tr> An on-finish-render directive triggers an event upon completion of t ...

Learn how to break down Angular 2 with Typescript in just 5 minutes by troubleshooting issues

I've been delving into the world of TypeScript and Angular 2 by following the guide at https://angular.io/guide/quickstart. After going through all the steps, I encountered some errors with the final step npm start. Here's what I got: Microsoft ...

show additional worth on the console

Just starting out with JavaScript. Trying to display additional values in the console. Uncertain about how to access add-ons. Can anyone help me troubleshoot? Here is my code snippet below: https://jsfiddle.net/6f8upe80/ private sports: any = { ...

Tips for developing an npm package that includes a demonstration application

When creating packages, I believe it's important to include a demo app. However, I'm unsure about the best way to organize the file structure for this purpose. My goal is to have one Github repository containing both my published NPM module and ...

Next.js throws a ReferenceError when the self variable is not defined while creating a child process using a custom webpack configuration

Trying to create a child process in Next.js for a time-consuming operation. Here is the webpack configuration (next.config.js): const { merge } = require('webpack-merge'); module.exports = { webpack: (config, { buildId, dev, isServer, defaultL ...

Array Filtering with Redux

I have come across similar queries, but I am still unable to find a solution. While typing in the search box, the items on the screen get filtered accordingly. However, when I delete a character from the search box, it does not show the previous items. For ...

A step-by-step guide on retrieving information from Material UI components and incorporating an onSubmit feature to transmit data to the backend server

I've recently started working with react/material-UI. While working on a project, I turned to youtube videos and various resources for guidance. I opted for material-UI due to its user-friendly nature. However, I'm currently facing a challenge ...