How can we efficiently assign an array of JSON responses using Observables and map within a TypeScript interface, and then display it in HTML using *ngFor in Angular 2?

export interface Relation{
name: string;
address: string;
dob: number;
}

The JSON response I received is as follows:

[ {"name":"John", "address":"xyz", "dob":"2000-01-10"},
{"name":"Jamie", "address":"abc", "dob":"1990-01-10"}
]

The issue seems to be with mapping the response to the Interface.

relations:Relation []=[];
getRelations() : Observable<Relation[]> {
   return this.http.get('url for json response').map(this.extractData).do(data=>console.log("Get all responses"+JSON.stringify(data))).catch(error => this.errorMessage = error);
}

extractData( response : Response){
let body = response.json();
console.log("Body", body);
return body.data;
}

When calling the getRelations method, it returns nothing.

ngOnInit(){
   this.getRelations().subscribe(relations=> relations, error=> this.errorMessage=<any>error);
}

Trying to display the data in HTML as table rows does not show anything. This indicates a problem either with initializing the Relation[] array or missing some key information.

Displaying the data using ngFor loop also does not work.

<tr *ngFor="let row of relations"> 
<td> {{row.name}} </td>
<td> {{row.address}} </td>
<td> {{row.dob}} </td>
</tr>

Answer №1

One issue is that the response lacks an object named data, instead it's just an array. Therefore, you should modify your extractData function to either return the response as-is or an empty array:

extractData( response : Response){
  let body = response.json();
  console.log("Body", body);
  return body || []; // Adjust here!
}

In addition, make sure to assign the data to a variable in your component:

this.getRelations()
  .subscribe(relations=> {
     this.relations = relations
  });

Furthermore, remember to use interpolation {{ }} in your template to display the objects and their properties:

<table>
  <tr *ngFor="let row of relations"> 
    <td>{{row.name}}</td>
    <td>{{row.address}}</td>
    <td> {{row.dob}}</td>
  </tr>
</table>

It appears that you are handling everything in the component, while typically we use a service to manage HTTP requests and mapping, with the component simply subscribing.

Service:

@Injectable()
export class Service {

  constructor(private http: Http) { }

  getRelations() : Observable<Relation[]> {
    return this.http.get('url')
     .map(this.extractData)
     .catch(error => console.log(error));
  }

  extractData( response : Response){
    let body = response.json();
    console.log("Body", body);
    return body || [];
  }

}

and in component:

constructor(private service: Service){}

ngOnInit(){
  this.service.getRelations().subscribe(relations=> {
    this.relations = relations;
  });
}

DEMO

Answer №3

Update your user interface to:

export interface Connection{
username: string;
location: string;
birthdate: string;
}

birthdate should be of type string, not number.

In addition, like Ben mentioned, make sure you either assign the response to connections, or ensure that part of the code is included.

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

The File is not being successfully sent to the controller in MVC due to AJAX returning an undefined value

I recently created an AJAXUpload method within a cshtml file in my C# MVC project: function AjaxUpload(url, method, data, successFunction, errorFunction, skipErrorDlg) { $.ajax({ contentType: false, processData: false, url: url ...

Separating text for tooltips from the element itself

I'm looking to enhance my website by adding tooltip descriptions to elements based on their CSS classes. While tooltips are usually added using the element's title attribute, I have numerous elements with the same lengthy description and want to ...

What is preventing me from refreshing my customized list view using the API?

Seeking assistance to customize a ListView using API data. Currently, the data is displayed as two TextView items instead of Title and Subtitle with an icon in the desired layout format. Looking for guidance on how to show the Line name as a row heading ...

Unable to clone curved text in fabric.js version 5.3.0

I am currently using fabric.js version 5.3.0 and I have a requirement to clone curved text and add it to the canvas. Description: The issue I am facing is that the cloning functionality does not work properly with curved text. The cloned object does not r ...

Is there a way for me to receive the response from the this.$store.dispatch method in vue.js 2?

Here is the structure of my component : <script> export default{ props:['search','category','shop'], ... methods: { getVueItems: function(page) { this.$store.disp ...

Preserve Text Selection While Utilizing DIV as a Button

I wonder if this issue is specific to the browser I'm using? Currently, I'm using Chrome... My goal is to enable users to save any text they've highlighted on the page with their cursor. I've set up the javascript/jQuery/ajax and it w ...

"Stellar.js fails to function properly when applied to elements loaded dynamically through AJAX requests

I recently implemented the amazing Stellar.js for parallax effects in a project of mine. However, I've encountered an issue: Stellar.js does not recognize when I update content via AJAX (specifically loading new div elements from an HTML file and rep ...

Is it possible to receive returned string values using fetch()?

I have implemented a fetch method in my separate register.js file to handle registration on the front end. However, I am encountering an error when trying to POST the data and receive the following message in the browser console: "Uncaught (in promise) Syn ...

Tips for speeding up the loading of JSON with large data on HTTP requests or webpages

When requesting the page (via HTTP or webpage), it seems to be very slow and even crashes unless I load my JSON data with fewer entries. This issue is critical as I anticipate needing to work with large amounts of data frequently in the future. Below are t ...

Switch back and forth between two tabs positioned vertically on a webpage without affecting any other elements of the page

I've been tasked with creating two toggle tabs/buttons in a single column on a website where visitors can switch between them without affecting the page's other elements. The goal is to emulate the style of the Personal and Business tabs found on ...

Shutting down the jQuery pop-up

I am struggling with trying to display this code as a popup on my website. Here is the code I have: <div id="myDialog" title="myTitle"> <div class="table_cell"> <div class="message"></div> </div> <div class="tabl ...

Alternate CSS options for controlling printing besides page-break-after and page-break-before

I am in the process of creating a web interface for printing barcodes on Avery label sheets. How can I ensure that the barcodes align perfectly on each label, using measurements like inches or centimeters? And most importantly, how do I prevent the barcode ...

The CORS Policy has prevented Angular from accessing the header, as the request header field for authentication is restricted

After reviewing a multitude of similar questions regarding CORS and headers, I have attempted various solutions but I am still encountering this error specifically in Google Chrome. Access to XMLHttpRequest at 'https://service.domain.com/clientlist&ap ...

What is the proper way to convert nil to JSON as nil, without representing it as an empty value?

I'm facing an issue in my controller/action where some values turn out to be nil: def my_action @var1 = get_boolean_value || nil @var2 = get_int_value || nil @var3 = get_string_value || nil # there are many more values, any of them might be ...

One way to dynamically track if any radio buttons in a group have been selected is by utilizing JQuery

Even though there are many related resources for this question, I still need a flawless solution. I have dynamically generated five groups of radio buttons. Each group contains up to five radio buttons. I have separately validated "none checked in" and "a ...

Tips for integrating an express-ws route

UPDATE: I had to properly configure express-ws: const express = require('express'); let expressWs = require('express-ws'); expressWs = expressWs(express()); const app = expressWs.app; const router = express.Router(); const createErro ...

What does the error message "TypeError: Bad argument TypeError" in Node's Child Process Spawn mean?

Every time I execute the code below using node: var command = "/home/myScript.sh"; fs.exists(command, function(exists){ if(exists) { var childProcess = spawn(command, []); //this is line 602 } }); I encounter this error: [critical e ...

Fatal error: The street number index is not defined

I am facing an issue with displaying decoded JSON data in my view. When I try to access the streetNumber index, I receive the following error: ErrorException (E_ERROR) Undefined index: streetNumber Below is a snippet of the data: array(11) { [0] ...

Troubleshooting Angular 2: Why Array Interpolation is Failing

Greetings everyone, I am diving into Angular 2 and attempting to create a basic Todo application. Unfortunately, I've hit a roadblock. My array interpolation seems to be malfunctioning. Any assistance would be greatly appreciated. Here is my AppCompo ...

Encountering an 'undefined' property error when clicking a button in Angular 1.x

Hey there, I have a question that might seem simple to some of you. I'm struggling with fixing an error and I don't quite understand why it's happening :( This error popped up while using Angular 1.x. What I need help with is creating an al ...