How to retrieve data from a JSON file in Angular 2 using the http get

I am encountering an issue while trying to access a json file using http get. The error message I receive is as follows:

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

Any assistance in identifying the problem would be greatly appreciated.

import { Component } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import { Http, Headers, RequestOptions, Response } from '@angular/http';

import { peopleService } from './PeopleService';


@Component({
selector: 'my-app',
templateUrl: './app.component.html',
//providers: [peopleService]
})

export class AppComponent {
//jsonFile: string = './EmployeeHeader.json';
empdata: Observable<Array<any>>[];

constructor(private http: Http) {
    this.http.get('../assets/EmployeeHeader.json')
        .map(Response => Response.json())
        .subscribe(empdata => this.empdata = empdata, error => console.log(error));
    //this.empdata = service.getPeople();
    //console.log('Data is: ' + this.empdata);
}
}

Below is the HTML code for reference,

<tbody>
<tr *ngFor="let t of empdata">
<td>{{t.wwid}}</td>
<td>{{t.name}}</td>
<td></td>
<td></td>
<td></td>
<td>{{t.idsid}}</td>
<td></td>
</tr>
</tbody>

https://i.stack.imgur.com/o6SYB.png

Here is the JSON format of the code for your reference, though I am unsure if any issues are present within it:

   {
"Employee":
[
  {
    "name": "Karthik Shekhar",
    "wwid": "11597210",
    "idsid": "kshekh1x",
    "costCenterCode": "80790",
    "mgrWWID": "10693268",
    "orgUnit": "67926"
  },
  {
    "name": "Aneesur Rahman",
    "wwid": "11744439",
    "idsid": "aneesurx",
    "costCenterCode": "32406",
    "mgrWWID": "10693268",
    "orgUnit": "67926"
  },
  {
    "name": "Ashutosh Pandey",
    "wwid": "11691980",
    "idsid": "ashuto3x",
    "costCenterCode": "32406",
    "mgrWWID": "10693268",
    "orgUnit": "67926"
  },
]
}

Answer №1

It seems like your empdata is actually an object and not an array. To properly access the Employee property within your object, you can do the following:

constructor(private http: Http) {
    this.http.get('../assets/EmployeeHeader.json')
        .map(Response => Response.json())
        .subscribe(empdata => {
            // accessing Employee property
            this.empdata = empdata.Employee
        }, error => console.log(error));
}

Answer №2

Revamp your service in the following way:

this.http.get('../assets/EmployeeHeader.json')
            .map(response => response.json())
            .subscribe(data => {this.data = data.Employee}
    , error => console.log(error));

Alternatively, you can update the *ngFor to:

<tbody>
<tr *ngFor="let item of data.Employee">
<td>{{item.wwid}}</td>
<td>{{item.name}}</td>
<td></td>
<td></td>
<td></td>
<td>{{item.idsid}}</td>
<td></td>
</tr>
</tbody>

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

Obtain JSON information and integrate it into an HTML document with the help of

I am currently working on a PHP/JSON file named users-json.php. <?php include_once('../functions.php'); if (!empty($_GET['id'])) { $GetID = $_GET['id']; $query = "SELECT Username, Firstname WHERE UserID = :ID"; $stmt = $d ...

Tips for accurately determining the count, rather than the character length, of JSON data

After running my code, I believe it returns a JSON array. The resulting JSON array is then stored in a JavaScript variable called 'result'. When I console.log(result); in Firefox, the output shown is: [{"id":"G24","value":"Zas, S"},{"id":"G75" ...

Reset dropdown selection when a search query is made

Currently experimenting with Angular to develop a proof of concept. Utilizing a functional plunker where selecting an option from a dropdown populates a list of items from an $http.get( ). Additionally, there is a search input that should trigger its own $ ...

Using ExtJS to populate a panel with data from various sources

I am currently working with an Ext.grid.GridPanel that is connected to a Ext.data.JsonStore for data and Ext.grid.ColumnModel for grid specifications. Out of the 10 columns in my grid, 9 are being populated by the json store without any issues. However, I ...

Tips on extracting the image URL after uploading via Google Picker

I'm currently implementing the Google Drive File Picker on my website for file uploading. Everything seems to be working well, except I am facing an issue with retrieving the image URL for images uploaded through the picker. Below is my current JavaSc ...

Vue: Optimizing JSON response filtering

I am struggling with filtering a JSON response using Vue. return this.offers.filter(type => type.offers == 'Junior'); When I keep it as return this.offers, the following is displayed in my HTML: {"-MN5agCddYAdy7c8GSSz": { "comp ...

In need of assistance with Ember data! Struggling to deserialize JSON into model

Here is the technology stack I'm currently using: Ember 1.10.0 Ember Data 1.0.0-beta.15 Within my application, I have defined a model as shown below: //models//acceptedtask.js import DS from "ember-data"; export default DS.Model.extend({ userAg ...

Error: Cannot read property 'X' of undefined in JavaScript when using Django framework

Using p5.js, I am creating drawings with data from a JSON provided by my Django backend. The draw function is defined at the base level of my HTML document within the script element: function draw(json) { if (json["leaf_text"]) { stroke(100) el ...

Ensure that the alert for an Ajax JSON record count remains active when the count is

Trying out Ajax JSON for the first time has been a bit tricky. Even though I hard coded "Record: 1" on the server side, it keeps alerting me with a total record of 0. I'm not sure where I went wrong. Could it be an issue with how I passed the array da ...

Strip away double quotation marks from object attributes except those beginning with a number

I've searched extensively and reviewed various Q&A forums, but I haven't encountered a scenario quite like this. Here's an example of the object I'm working with: props: { "label": "1rem", "text3": "1rem", "text2Button": "1re ...

Highcharts: single point muted and not easily seen when markers are turned off

Highchart displaying data with some null points (only visible via tooltip if marker disabled): https://i.stack.imgur.com/u04v1.png https://i.stack.imgur.com/uRtob.png Enabling markers will resolve the issue of invisible points, but it may look cluttered ...

What do you prefer: defining properties with the JSON object or with objectName.property in JavaScript

Can you tell me which approach is considered the best practice? Is it better to use the "this" statement in the following way: var obj = { x: 20, y: 10, width: this.x, height: this.y, render: function () { // renders object on canvas ctx.fi ...

Utilize recursive and for loop methods for parsing JSON efficiently

I have a JSON file that requires parsing. I'm attempting to implement a recursive method for this task. The current JSON data is structured as shown below: Item 01 SubItem 01 InnerSubItem 01 Item 02 SubItem 01 InnerSubItem 01 Unfortunately, t ...

Implementing onClick functionality in RecyclerView post JSON data extraction

I recently implemented a RecyclerView in a fragment and successfully parsed JSON data from a website to display it in the RecyclerView following a helpful tutorial found at: Now, my next challenge is adding an onClick listener to the items in the Recycler ...

A guide on organizing nested JSON objects in JavaScript

I am currently using JavaScript to retrieve JSON data that looks like this: [{ "data": { "serialNumber": "12345678", "loopCount": 2, "temperature3": 22.74921781259558, "temperature2": 21.459065450414467, "temper ...

The module located at "c:/Users//Desktop/iooioi/src/main/webapp/node_modules/rxjs/Rx" does not have a default export available

I am currently delving into the realm of RxJs. Even after installing rxjs in package.json, why am I still encountering an error that says [ts] Module '"c:/Users//Desktop/iooioi/src/main/webapp/node_modules/rxjs/Rx"' has no default export ...

Can JSON.parse be used on only a portion of an object in JavaScript?

Currently, I am facing an issue with a lengthy JSON file that I am fetching from a URL using https.request. Upon attempting to parse the string with JSON.parse, I encounter an "Unexpected end of JSON input" error. It appears that there is a limit to the ...

Extracting information from a string with JSON in Javascript

Can you assist me? I have developed a web service that provides a clean string after clicking on the URL: { "PersonID": 125, "Title": "Security Officer", "Company": "TSA", "CellNum": "423-915-3224", "EmergencyPhone": "", "Email": " ...

Displaying properties of objects in javascript

Just starting with JavaScript and struggling to solve this problem. I attempted using map and filter but couldn't quite implement the if condition correctly. How can I find the records in the given array that have a gender of 0 and color is red? let s ...

Retrieve the unique identifier of a single post from a JSON file within a NuxtJS project

Is there a way to retrieve the unique post id data from a JSON file in NuxtJS? created() { this.fetchProductData() }, methods: { fetchProductData() { const vueInstance = this this.$axios .get(`/json/products.json`) ...