Leveraging TypeScript in Angular 4 for parsing response data

I have received the following response data:

{
  "content": [{
    "id": 1,
    "userName": "v7001",
    "status": 1,
    "userInfo": {
      "id": 1,
      "fullName": "Naruto Uzumaki",
      "firstName": "Naruto",
      "lastName": "Uzumaki",
      "address": "Konoha",
      "dob": 1509901200000
    }
  }, {
    "id": 2,
    "userName": "v7002",
    "status": 0,
    "userInfo": {
      "id": 2,
      "fullName": "Hinata Hyuga",
      "firstName": "Hinata",
      "lastName": "Hyuga",
      "address": "Konoha",
      "dob": 1509987600000
    }
  }],
  "last": true,
  "totalElements": 3,
  "totalPages": 1,
  "size": 20,
  "number": 0,
  "first": true,
  "sort": null,
  "numberOfElements": 3
}

and I am using Angular 4 to display this data. I have created 2 interfaces: User-info

export class UserInfo {
  id: number;
  fullName: string;
  firstName: string;
  lastName: string;
  address: string;
  dob: string
}

and User

import {UserInfo} from './user-info'

export class User {
  id: number;
  userName: String;
  status: String;
  userInfo: UserInfo;
}

User service :

getUsers(): Promise<User[]> {
  return this.http.get(this.userUrl)
    .toPromise()
    .then(response => response.json().data as User[])
    .catch(this.handleError);
}

I checked in the network tab, and the API successfully retrieved data. In the component:

user: User[];
selectedUser: User;
newUser: User;
data: any={};

constructor(private router: Router,
            private userService: UserService) {}

ngOnInit() {
  this.userService.getUsers().then(user => this.user = user); 
}

and in the html:

 <tr role="row" class="odd" *ngFor="let lst of user.content">
   <td>{{lst.userInfo.fullName}}</td>
   <td>{{lst.userInfo.address}}</td>
</tr>

However, when running the app, an error message is displayed on the console: 'content invalid'. The 'this.user' is undefined. Please advise me on how to resolve this issue.

Answer №1

If you are anticipating the retrieval of a 'users' collection from the 'getUsers' method, ensure that you return 'response.json().content' instead of 'response.json().data'. This way, using 'User[]' would be more appropriate to facilitate tooling for the collection as 'User[]'.

getUsers(): Promise<User[]> {
  return this.http.get(this.userUrl)
    .toPromise()
    .then(response => response.json().content as User[])
    .catch(this.handleError);
}

Utilization

this.userService.getUsers().then(users => this.users = users);

HTML

<tr role="row" class="odd" *ngFor="let lst of users">
  <td>{{lst.userInfo.fullName}}</td>
  <td>{{lst.userInfo.address}}</td>
</tr>

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

I am encountering an issue where my useState value is coming back as undefined after I fetch data. It appears that the useState hook is

import React, { useEffect, useState } from 'react'; function MainContent() { const [objectsArr, setObjectsArr] = useState(null); useEffect(() => { async function fetchData() { let response = await fetch('http ...

Create duplicates of both the array and its individual elements by value

I'm having trouble figuring out how to properly copy an array along with all its elements. In my model, I have a name and options, both of which are strings. This is what I currently have: const myArrayToDuplicate = [myModel, myModel, myModel] My ...

Intelligent Scrolling with Bootstrap 4

Utilizing a basic tutorial from here to implement show/hide functionality for a standard BS4 navbar on scroll. Works flawlessly on desktop. However, facing an issue with the mobile view where the navbar behaves oddly when scrolling down and returning to t ...

Slim 4 with Angular 10: Issues with downloading PDF files through API, as Angular blob response is coming back empty

Struggling to integrate the download PDF Angular API with Slim 4 API. The response from Slim can be seen in the browser network, but when trying to parse it in Angular, it comes back empty. All the necessary headers have been added on both Angular and Slim ...

Can someone please point me in the right direction to locate a Typescript project within Visual Studio

I've been struggling with this issue for days and still can't find a solution. After installing the Typescript tool for Visual Studio 2015, it appears to be successfully installed. https://i.stack.imgur.com/nlcyC.jpg However, I am unable to loc ...

Yii2 paired with Ajax: The output does not consist of the SQL query outcomes

I am facing an issue with executing an AJAX query using jQuery as the response is not as expected. On the client side: $.ajax({ url: "/family?idperson=1234", dataType: 'json', success: function(res) { console.log(JSON.string ...

JavaScript: Issue with launching Firefox browser in Selenium

I'm currently diving into Selenium WebDriver and teaching myself how to use it with JavaScript. My current challenge is trying to launch the Firefox browser. Here are the specs of my machine: Operating System: Windows 7 64-bit Processor: i5 Process ...

Angular click event not functioning properly on elements loaded via http request

Check out my CodePen link: http://codepen.io/gauravcoder/pen/vLWEjJ?editors=101 I'm just getting started with Angular JS. I have some items that trigger an alert when clicked, it works fine for items that are not loaded via an HTTP request. However, ...

add the closing </div> tag using jquery only

Having a slight issue here, it seems that jQuery is being overly clever. Within my HTML code, I am attempting to insert this string into a div container: </div><div class="something"> You'll notice that the closing tag comes first, foll ...

Troubleshooting Problems with CSS `transform` in JQuery UI's `Slide` Transition

While implementing JQueryUI's slide transition on an element with a CSS transform, I encountered an issue where the top half of the element gets hidden during the animation. Is there a way to tweak either my JQueryUI animation or CSS to avoid this pro ...

NodeJS: The module failed to automatically register itself

Exploring the capabilities of IBM Watson's Speech to Text API, I encountered an issue while running my NodeJS application. To handle the input audio data and utilize IBM Watson's SpeechToText package, I integrated the line-in package for streami ...

Managing Angular Universal in a production environment can be a challenging task

I am currently working on a project that utilizes the MEAN stack. Front-end: Angular 6.*. Backend: ExpressJs and Mongodb. During development, Angular runs on port 4200, while ExpressJs runs on port 3000. For production, I build Angular and serve it as ...

The negative z-index is causing issues with my ability to select classes using jQuery

By setting a z-index of -3 for several divs in my background, I thought they wouldn't affect the formatting of elements in the foreground. But now I'm facing an issue where I can't click on those background divs when trying to target them wi ...

Mobile Devices and Local Storage: What You Need to Know for Safe and Efficient Use. Looking for advice from experienced developers

Need help with caching user input on an Angular11 + Firebase app? Let's discuss implementing a caching feature for a dynamic form section that can contain varying fields based on the use case. The goal is to save user input in LocalStorage to ensure ...

How can I effectively utilize the Metamask SDK with TypeScript?

Currently, I am in the process of developing a webpack+pnpm+typescript+react website. All the versions being used are LTS and my preferred IDE is VSCode. According to the guide provided by Metamask here, it seems like I need to follow these steps: npm i @m ...

Retrieving document attributes from a Mongoose Model with the help of Typescript

Incorporating Typescript with Mongoose, my aim is to retrieve properties from a Model. Taking the illustrated UserModel as an example import mongoose, { Schema } from 'mongoose'; const userSchema: Schema = new mongoose.Schema({ _id: mongoos ...

Having trouble importing XML data from an external file with jQuery

Attempting to import external XML with the code below is proving unsuccessful $( document ).load( "data.xml", function( response, status, xhr ) { console.log( xhr.status + " " + xhr.statusText ); }); Both data.xml and js files are in the ...

Using AJAX to retrieve JSON information

Looking for advice on improving my script to fetch JSON data from a server file using AJAX. I am struggling with organizing it into a functional structure. Below is the current implementation: function getJSON (file) { var request = AjaxRequest(); ...

Why is the "class" attribute of an SVG node not being applied when I change it?

I am having trouble changing the "class" attribute of a node in SVG using my AngularJS Directive. Even though I've written the code to do so, it doesn't seem to be applied properly. This is the code snippet from my Directive: node = node.data(f ...

"Utilizing Bootstrap to create a multiselect feature that can dynamically

I am facing an issue with receiving alerts for dynamically added bootstrap select elements <html> <head> <link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet" type="text/css" /> <link hr ...