The error message "NgFor only supports binding to Iterables such as Arrays" is triggered even though the JSON response is formatted as an array

Using TypeScript in CompanyComponent Class

export class CompanyComponent  {
  apiService : APIService;
  data : any;
  private companyUrl = 'http://localhost:4000/api/company/';

  constructor(apiService : APIService) {
    this.apiService = apiService;
    this.retrieveCompanies(this.companyUrl);
  }

  retrieveCompanies(url: any){
    this.data = this.apiService.GET(url).map((response :Response)=>
    response.json()).subscribe((response)=>{
    this.data = response;
    console.log(this.data);
  })
}

Array Response from Server

[
   {"_id":"58f61a132d44240d085ca2fa","comapny_name":"Burslem 
  Spice","__v":1,"categories":["58f643382d44240d085ca2fb"]},<br>
  {"_id":"590487964a45c56c0fa2911a","comapny_name":"Tiger 
  Bite","categories":[]}
]

HTML Template for Displaying Data

<div class="media">
  <div class="media-left" >
    <li class="media" *ngFor = "let comp of data" >
      <label>{{comp}}</label>
    </li>   
  </div>  
</div>

The server's response is an array, but I am encountering the following error:

ERROR caused by: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

https://i.sstatic.net/E9tOV.png

Answer №1

data : any; suggests that data can take on any value, but *ngFor only works with Iterables. To avoid issues, use array instead. Since data is loaded asynchronously, it may be undefined when the DOM first renders, causing Angular to throw an error.

 export class CompanyComponent  {
      apiService : APIService;
      data : Array; // or array
      private companyUrl = 'http://localhost:4000/api/company/';

constructor(apiService : APIService) {
        this.apiService = apiService;
        this.getCompanies(this.companyUrl);
        this.data = [];
}

getCompanies(url: any){
        this.apiService.GET(url).map((response :Response)=>
        response.json()).subscribe((response)=>{
            this.data = response;
            console.log(this.data);
        })
}

HTML

<div class="media">
  <div class="media-left" >
      <li class="media" *ngFor = "let comp of data" >
          <label> {{comp.company_name}}</label>
      </li>   
  </div>  
</div>

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

How to link AngularJS controller from a different module in routing

My current project involves creating a complex app with a structured design: Each module is organized in its own folder structure, including controllers, directives, and more. Within each folder, there is an index.js file along with other files for separ ...

Unable to find solution for 'rxjs-compat/observable/combineLatest'

Recently, I updated my angular project to utilize "rxjs": "^6.3.3" Incorporating the combineLatest operator has caused complications after the upgrade, leading to compilation errors ERROR in ./node_modules/rxjs/observable/combineLatest.js Module not fo ...

Retrieve the decimal separator and other locale details from the $locale service

After reviewing the angular $locale documentation, I noticed that it only provides an id (in the form of languageId-countryId). It would be helpful to have access to more specific information such as the decimal separator character. Is there a way to retri ...

Why isn't my computed property functioning properly in Vue.js?

Exploring the code snippet provided below: new Vue({ el: '#app', computed: { myMessage: function() { return "hello"; } }, data: { message: this.myMessage }, mounted: function() { console.log(this.myMessage); ...

Utilizing numerous X-axis data points in highcharts

I'm working with a line graph that dips straight down, like starting at (1, 100) and dropping to (1,0). The issue I'm facing is that Highcharts (https://www.highcharts.com/) only displays information for one of the points. Is there a way to make ...

Is there a way to refresh my order hook in React JS?

I've been attempting to modify the values within my order hook, but for some reason, they aren't updating. I'm relatively new to React and can't figure out what mistake I might be making. Any insights? Take a look at my code snippet: ...

Information is not transferring to Bootstrap modal

I attempted to send a value to a modal by following the instructions on the Bootstrap documentation here. However, I am facing an issue where the data is not being successfully passed. To trigger the modal, use the following button: <button type=" ...

Using Jquery to dynamically link a textbox with the onload event: A Guide

When a user clicks a button, a textbox is dynamically created in Javascript. It appears on the screen to be filled by the user. <input type="text" id="documentTitle" name="documentTitle" value="<spring:message code="document.Title"/>" I am looki ...

Utilizing the components within the range set by paper.setStart() and paper.setFinish() in Raphaels

My question has two parts - the first and second part. Let's consider an example code that I am working on. I am creating a map of my country with regions, and I want to perform actions on the entire map such as scaling or translating (as seen in the ...

Developing with Phonegap Build: A Guided Process

With all the conflicting information available, I am seeking clarity on this topic. Objective: To create and enhance a Phonegap app using Phonegap Build. 1) My preference is to utilize Phonegap Build without needing to install Android and iOS SDKs. 2) I ...

Instructions on sending an array of objects containing a file via ajax to an ASP.NET MVC controller

https://i.sstatic.net/2bjPF.jpg I have been attempting to send multiple rows, each containing a single file (as shown in the image above), to my MVC controller using ajax. Here is the JavaScript code I am using- var formData = new FormData(); $('#as ...

EaselJS - Utilizing multiple canvases with varying frame rates

Currently, I am exploring EaselJS by creating two animation instances using sprite sheets on two separate canvases positioned at different locations but with the same z-index. The issue I am facing is that these instances are not layered properly. My setup ...

A guide on cropping and uploading images using ejs and Node.JS

Currently I am utilizing JQuery to crop an image. <link href="/public/css/jquery.Jcrop.min.css" rel="stylesheet" type="text/css" /> <!-- add scripts --> <script src="http://code.jquery.com/jquery-1.9.0.js"></script& ...

Having trouble getting the ReactJS AXIOS post function to work properly?

Error in console: [1]: https://i.sstatic.net/xOfUV.png issue with axios request .post("https://bootcamp-2022.devtest.ge/api/application", { token: "7e475dfc-0daa-4108-81c8-d6c62a3df4ca", first_name: JSON.parse(localStorage.ge ...

JavaScript encounters a parsing error when dealing with an async function

Ever since I developed a node.js web application, I've been utilizing MSSQL for the database. To streamline SQL functions, I crafted functions (sql.js) to handle all the necessary queries. Furthermore, I set up async function handlers (controllers.js) ...

Having trouble aligning the canvas of threejs next to a div

I am currently working on a shoe customizer project and facing difficulties in aligning my canvas (using three.js) next to the shoe customizer div. Although I posted the same question earlier, I did not receive a satisfying solution. I made some adjustment ...

Turning XSD into TypeScript code

Stumbling upon this tool called CXSD, I was intrigued. The documentation describes cxsd as a streaming XSD parser and XML parser generator designed for Node.js and TypeScript (optional but highly recommended). It seemed like the perfect solution for my ne ...

unable to fetch information from OdooRPC

I've encountered an issue while trying to fetch data from the database using jsonRpc through the Odoo API. The error message I received was "HTTP/1.1 GET /projects - 404 Not Found". Below is the snippet of my code: A Python script used for data mani ...

What is the best way to change the value of a div using JavaScript?

i could really use some assistance, i am trying to ensure that only the selected template is shown on the screen, while all others are hidden. The expected outcome should be to replace the values of: <div class="city">City<span>,< ...

The AngularJS Factory $http encounters an error when attempting to read the property 'length' of an undefined value

I am looking to implement a factory in my REST Controller that will return an array of Strings. I want to be able to reuse this function in my services.js file. Here is the HTML for an Autocomplete input field: <input type="text" ng-model="vertrag.ver ...