Open the JSON file and showcase its contents using Angular

I am attempting to read a JSON file and populate a table with the values. I've experimented with

this.http.get('./data/file.json')
   .map(response => response.json())
   .subscribe(result => this.results =result,
    function(error) { console.log("Error happened" + error)}, 
    function() { console.log(this.results)});

as well as:

this.http.get("./data/file.json")
  .map(response => { return <ITest[]>(<ITest[]>response.json())})
  .subscribe(result => this.results =result,
    function(error) { console.log("Error happened" + error)}, 
    function() { console.log(this.results)});

However, I keep receiving undefined in the console. The GET request appears fine as the response is visible in the network view in the debugger. I'm unsure of what I might be missing.

The HTML structure is as follows:

 <ng-container  *ngFor='let stat of results;let i = index' [attr.data-index]="i">
   <tr>
      <td style="text-align:left!important;" class="table-row">{{stat.Name}}</td>
      <td class="table-row"> </td>
      <td class="table-row">{{stat.Age}} </td>
   </tr>
   <tr *ngFor="let subitem of stat.Intervals">
      <td style="text-align:right!important;">{{subitem.StartDate}}</td>
      <td>{{subitem.EndDate}}</td>
      <td >{{subitem.Duration}}</td>
   </tr>
</ng-container>

Answer №1

Instead of using the function() syntax, opt for the arrow operator =>. By doing so, you avoid losing the scope of this which can result in getting undefined.

    this.http.get('./data/file.json')
                      .map(response => response.json())
                      .subscribe(result => this.results =result,
                         error=> console.log(error),
                         () => console.log(this.results));

Answer №2

Avoid using async in the template when manually subscribing to data. Only use async if you are not using subscribe, as it handles the subscription process automatically.

It is recommended to utilize fat arrow syntax to maintain the context of this, as suggested by Amit. Update your code to match Amit's suggestion:

this.http.get('./data/file.json')
   .map(response => response.json())
   .subscribe(result => this.results = result,
     error=> console.log(error),
     () => console.log(this.results));

The reason why nothing is being displayed in the template could be due to incorrect property names. Remember that property names are case sensitive, so make sure to use stat.Name and stat.Age based on the properties you mentioned in your comments.

<ng-container *ngFor='let stat of results; let i = index' [attr.data-index]="i">
   <tr>
     <td style="text-align: left!important;" class="table-row">{{stat.Name}}</td>
     <td class="table-row"></td>
     <td class="table-row">{{stat.Age}} </td>
   </tr>
</ng-container>

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

Error message "Unknown web method DoesUserExist. Parameter name: methodName" occurs when trying to pass a JSON value to a Web Method

Greetings, here is the JavaScript code I am working with: <script type="text/javascript"> $(document).ready(function () { function validateEmail(email) { var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2, ...

Execute the script using ajax

Is it possible to execute JavaScript within an AJAX request? I attempted to include some JavaScript code in the PHP file that was called by an AJAX command. The purpose of this script was to modify an HTML attribute on the parent page. However, it did not ...

Tips for effectively managing relationships in a RESTful API

Exploring the concept of REST architecture through the development of a RESTful service for an 'Issues Tracking Application'. In this application, users, projects, issues, and comments are integral components. The relationships are outlined as f ...

Show the loader animation until the browser's loading icon stops spinning

My website receives a high volume of traffic and pulls data from several servers to display on the page. It typically takes 3-4 minutes for the entire page to finish loading. Here is a preview of some of the partial page data: I am looking to add a spinni ...

How to shuffle the elements of an array saved in a JSON file using discord.js

I've been working on a Discord bot as a way to learn more about Javascript. While creating a command that pulls random quotes from an array stored in a separate JSON file, I encountered an issue that has me stumped. var config = require("./settings.j ...

Incorporate the ng2-ace library into a newly generated Angular-CLI (Angular2) project with the help of SystemJS

After setting up my angular2 project using the latest angular-cli tool, I decided to integrate the ace editor with the help of the ng2-ace library. My goal was to implement this in a clean manner using SystemJS as the module loader. I started by running ...

The download handler (php code) is being triggered multiple times within a single request

My PHP script is responsible for handling download requests. Clients can access this script using a GET request, as shown in the Javascript example below: if (true) { window.open('/download?mode=paper&fid=' + fid, '_blank'); re ...

Two paths for a single Angular component

Is it feasible to create two distinct routes that reference one component? Consider the following scenario: { path: 'login', component: LoginComponent }, { path: 'user/:id/login', component: LoginComponent } I'm inquiring about t ...

The combination of jQuery event handling and accessing undeclared event objects

While debugging someone else's code, I encountered a puzzling situation. The snippet of code provided below illustrates the problem. It seems to me that event should be undefined upon entering the event handler. This is indeed the case in Firefox, bu ...

Is there a way to assign separate names for serialization and deserialization in MVC?

I've encountered a situation where I have a class with attributes such as [DataContract] and [DataMember]. Specifically, the Name property of the Origin is set to custom variables, matching the data provided by the API I'm working with. However, ...

Encountering the (415) Unsupported Media Type issue

My current task involves sending JSON data to a specific URL. The structure of my JSON data is as follows: { "trip_title":"My Hotel Booking", "traveler_info":{ "first_name":"Edward", "middle_name":"", "last_name":"Cullen", ...

Failed Attempt to Execute React Native Application using Command Prompt (iOS)

I'm currently working through the React Native tutorial found on their official website. During my project building process, I utilized the following command: react-native run-ios An error was encountered: Found Xcode project TestProject.xcodeproj ...

What is the best way to access data from this $scope in AngularJS?

Upon printing selecteditems to the console, this is the output: [{"model":"Lumia","brand":"Nokia","subModel":["Lumia 735 TS","Lumia 510"],"city":"Bangalore"}] I have stored it in $scope.details as follows: var selecteditems = $location.search().items ...

Interacting with a JavaScript button using C# WebBrowser

Can someone please assist me with a problem I'm facing? I have a webpage coded in HTML and Javascript. Whenever I use webBrowser1.Document.GetElementById("hmenu").InvokeMember("click");, the menu pops up on my screen. However, I am unsure how to cli ...

Converting Dynamic Objects into Class Instances

I've been grappling with this issue for the past day or so and I just can't seem to pinpoint why it's occurring. Right now, my goal is to deserialize a dynamic object into a class for usage. However, no matter what I do, I keep encountering ...

The failure of jQuery AJAX error callback to execute

I'm currently facing an issue with an AJAX call that I have in my code. Here's the code snippet: $.ajax({ type: "get", url: "xxx.xxx.xxx/xxx.js", dataType: 'jsonp', success: function(data) { ...

Exploring the concepts of closure and scope

It seems that the function inResult always returns false and the loop is not being executed, probably due to a lack of understanding of closures. However, I can confirm that the result variable contains the correct properties. function hasId() {return ...

Tips for accessing a variable located in a different directory

I'm facing some confusion regarding creating a global variable that can be accessed in another file. Currently, I have a chat and login folder setup. Within the login folder, there are three possible users to choose from. When a user clicks on one of ...

ActiveModel::UnknownAttributeError (attribute 'order_items_attributes' is not recognized by Order model.):

Can someone please assist with this problem? ActiveModel::UnknownAttributeError (unknown attribute 'order_itens_attributes' for Order.): Here is the code from my controller: def create @order = Order.new(order_params) if @order.save ...

Lunar - incorporate route parameter into DOM query_operation

Is there a way to take a route parameter and use it to trigger a click event on a DOM element? The issue is that onBeforeAction is called before the DOM is fully loaded. Any suggestions on how to solve this problem? JS onBeforeAction: function(){ var ...