Tips and tricks for displaying JSON data in Angular 2.4.10

In my Angular project, I am facing an issue while trying to display specific JSON data instead of the entire JSON object.

Scenario 1 :

import { Component, OnInit } from '@angular/core';
import { HttpService } from 'app/http.service';
import { Response } from '@angular/http/src/static_response';

@Component({
  selector: 'app-httpapp',
  template: `
    <p>
      httpapp Works!
      <br><hr>
        {{t_obj | json}}
    </p>


    <div *ngFor="let t of t_obj">
        {{t.tname}}//not working
        {{t}}
    </div>
  `,
})
export class HttpappComponent implements OnInit {

  t_obj : T ;

  constructor(private httpService : HttpService) { }

  ngOnInit() 
  {
    this.httpService.getData()
    .subscribe(
      (data : Response) => {
        this.setData(data)
      }
    );
  }



  setData(response : Response)
  {
      this.t_obj = response.json();
      console.log(response.json());

  }
}//class

class T{
  tname : string;
}

output:

[ { "t": "A" }, { "t": "B" }, { "t": "C" ] 
Now i want to know that how can i show only data instead of the full json object.

Case 2 :

Below is my REST controller :

@RequestMapping("/greeting")
public T greeting()
    {
    return new T("Done..!");
    }

Angular code :

@Component({
  selector: 'app-httpapp',
  template: `
    <p>
      httpapp Works!
      <br><hr>
      {{t_obj.t}}
    </p>
  `,
})
export class HttpappComponent implements OnInit {

  t_obj : any ;

  constructor(private httpService : HttpService) { }

  ngOnInit() 
  {
    this.httpService.getData()
    .subscribe(
      (data : Response) => {
        this.setData(data)
      }
    );
  }

  setData(response : Response)
  {
      this.t_obj = response.json();
      console.log(response.json());
      console.log(this.t_obj.t);

  }
}//class

For case two i am getting the below error message :

EXCEPTION: Uncaught (in promise): Error: Error in ./HttpappComponent class HttpappComponent - inline template:3:14 caused by: Cannot read property 't' of undefined
Error: Error in ./HttpappComponent class HttpappComponent - inline template:3:14 caused by: Cannot read property 't' of undefined

After showing this error message it is printing the below lines :

{t: "Done..!"} Done..! 

So my question is, according to the error message if 't' is undefined then how it is being printed in console log.

Update : I got solution for case 1, i have to use {{t.t}}

Answer №1

Based on your code, the correct syntax should be {{t.t}} instead of using {{t.tname}}

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

It is advised not to use arrow functions to assign data when fetching API data with axios in Vue.js 2

Trying to retrieve data from a URL using Axios in my Vue app is resulting in the error message: Error: Arrow function should not return assignment Complete error message: Error: Arrow function should not return assignment (no-return-assign) at src\co ...

Extracting HTML elements between tags in Node.js is a common task faced

Imagine a scenario where I have a website with the following structured HTML source code: <html> <head> .... <table id="xxx"> <tr> .. </table> I have managed to remove all the HTML tags using a library. Can you suggest w ...

Leveraging JSON Data for Avatars in React.js

Struggling to arrange 10 Avatars side by side for showcasing the user list. However, encountering an issue where the Avatars are being duplicated and showing incorrect initials when passing JSON data. Experimented with this in Code Sandbox linked below. h ...

Arrange a JSON array in Python by two important values

I am working with a JSON list that has the following structure: [{ "id": "1", "score": "100" }, { "id": "3", "score": "89" }, { "id": "1", "score": "99" }, { "id": "2", "score": "100" }, { "id": "2", "score": "59" }, { "id": "3", "score": "22" }] My goa ...

Guide on utilizing the reduce method with objects

I am attempting to use the reduce method on an object to create an HTML list const dropdownTemplate = (data) => { console.log(data); // no data displayed return ` <li class="dropdown__item" data-value="${data.value}"><span class="dropdown__i ...

Avoiding code execution by injections in Javascript/Jquery

Currently, I'm fetching JSON data for a .getJSON function in Jquery. To ensure the data's security, I am considering using .text (I believe this is the correct approach). The JSON has been successfully validated. Below is the script that I am cu ...

How can I save variable values to a text file or Excel file using Cypress.io?

Is there a way to write the values of a variable on a Text or Excel sheet? I have a variable called tex that stores string values, and I want to output these values onto text files or an Excel sheet if possible. beforeEach(() => { cy.visit('ht ...

What is the best way to retrieve specific data based on their unique identifier?

Imagine having a table like this, with the following data: Id , Name , IsBillable 1 One 1 2 two 0 3. three 0 I have stored this data in a variable called masterData using the get method, and I am using it to populate a dropdown me ...

Looping through each combination of elements in a Map

I have a Map containing Shape objects with unique IDs assigned as keys. My goal is to loop through every pair of Shapes in the Map, ensuring that each pair is only processed once. While I am aware of options like forEach or for..of for looping, I'm s ...

Converting an AngularJS Array to Firebase JSON Format

Currently, in my application, I am working on creating an array using JS. $scope.items = []; As I add items to this array, I retrieve information from a Firebase Reference and populate the items array with it. es.addItem = function(item){ var produc ...

AngularJS seems to be failing to display the initial option in the input select field

When using Angularjs, binding an input select to the model results in a new empty option being created <option value="? undefined:undefined ?"></option> Here is an example of the code: <select name="category" ng-model="hotspot.category"&g ...

Tips on incorporating jstree into an Angular 2 application with TypeScript and @types/jstree

Hello, I am new to ng2 and have a question that may seem obvious to some. I recently installed the jstree library using npm in my angular-cli application by running the command npm i jstree --save. Following this, I also installed the types for jstree wi ...

Understanding the fundamental concepts of callbacks with Backbone.js

Currently, I am working with Backbone to send a login form to my server. Once the form is submitted and the database query is successful, a boolean value is flipped to enable GET responses from the server. However, the issue arises when it attempts to fetc ...

Is there a way to update components in Angular without affecting the current URL?

I want to update a component without changing the URL. For example, I have a component called register. When I visit my website at www.myweb.com, I would like to register by clicking on sign up. How can I display the register component without altering the ...

The rendering of the input dropdown control in Angular JS is experiencing difficulties

I am currently using your Angular JS Input Dropdown control, and I have followed the code example provided on your demo page in order to implement the control on a specific page of my website built with PHP Laravel. However, I have encountered an issue dur ...

When an HTML element is deleted, its events are not being removed as expected

I currently have events bound in my backbone view. sampleView = Backbone.View.extend({ events: { "click .sum": "sumButtonFunc", "click .diff": "diffButtonFunc" } sumButtonFunc: function(){ console.log("sum called") ...

Encountering a 'Not Found' error while deploying my React Node application with an AWS-hosted database on Heroku

const express = require("express"); const app = express(); const bodyParser = require("body-parser"); const port = process.env.PORT || 3002; const cors = require("cors"); const path=require("path"); const routing = ...

Is the size of the JSON file inhibiting successful parsing?

After retrieving a large list of schools with their respective columns from the database, totaling over 1000 rows, I converted it to JSON and passed it to my view. I then attempted to parse it using $.parseJSON('@Html.Raw(Model.subChoiceJsonString)& ...

Retrieve the content of a particular text input field that is accompanied by a checkbox, and then display this information within an

In this example, the "textbox" is currently empty and requires user input. The checkbox should mirror what is typed in the textbox (type="checkbox" value=written-text-on-profile-textbox) When the checkbox is selected, it should take the text entered in th ...

Failure to receive results from $.getJSON request

I am currently working on developing a web page that allows users to search and retrieve Wikipedia pages based on their search results. Below is the relevant HTML code for the search feature: <form class='search-form' onsubmit='return f ...