The process of linking a Json response to a table

In my products.components.ts class, I am retrieving Json data into the variable this.Getdata.

ngOnInit() {
this._service.getProducts(this.baseUrl)
.subscribe(data => {
  this.Getdata=data
  this.products=data
  alert(JSON.stringify(this.Getdata));      
});

I want to bind this Json data in the products.components.html class within a Table.

<p>
Product List
</p>
<table>
<th>Id</th> <th>Name</th> <th> Country</th> <th>Actions</th>
<tr *ngFor="let lst of products; let i = index" border="1">
  <td>{{i+1}}</td><td>{{lst.id}}</td><td>{{lst.employee_name}}</td> <td>Edit</td>
</tr>
</table>

The code above is not functioning correctly. Only the alert is being displayed. How can I successfully bind the data to the table?

This is the Json data I am working with:

[{"id":"1","employee_name":"amit","employee_salary":"0","employee_age":"0","profile_image":""},{"id":"247793","employee_name":"Ana","employee_salary":"123","employee_age":"123","profile_image":""},{"id":"247856","employee_name":"Joseph Beltran","employee_salary":"1000","employee_age":"23","profile_image":""},{"id":"247982","employee_name":"testyeyyeye1","employee_salary":"123","employee_age":"23","profile_image":""},{"id":"248007","employee_name":"test100","employee_salary":"123","employee_age":"23","profile_image":""},{"id":"248038","employee_name":"Hendry","employee_salary":"61888","employee_age":"26","profile_image":""}]

Model Class:

export class Productlist {
id: string;
employee_name: string;
employee_salary: string;
employee_age: string;
profile_image: string;
}

Answer №1

Opt for storing the Observable in a property instead of subscribing to it directly, and then use the async pipe in your template.

By following this approach, you can simplify your Component like so:

import { Component } from '@angular/core';
import { Observable } from 'rxjs';

import { EmployeeService } from './employee.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  employees$: Observable<Array<any>> = this.employeeService.getEmployees();
  constructor(private employeeService: EmployeeService) {}
}

Update your Template as shown below:

<p>
    Employee List
</p>
<table border="1">
    <thead>
        <th>Id</th>
        <th>Name</th>
        <th> Country</th>
        <th>Actions</th>
    </thead>
    <tbody>
        <tr *ngFor="let employee of employees$ | async; let i = index">
            <td>{{i+1}}</td>
            <td>{{employee.id}}</td>
            <td>{{employee.employee_name}}</td>
            <td>Edit</td>
        </tr>
    </tbody>
</table>

Explore this Live Demo Code for reference.

Note: Ensure to name your properties and methods appropriately according to the context; consistency matters when working with specific data entities like employees.

Answer №2

Another option is to utilize the following code:

const newObj= JSON.parse(jsonValue);

The object will now be accessible in newObj, allowing you to easily iterate through it using ngFor.

Answer №3

This is how I figured it out

class ProductListService implements OnInit {
public fetchData;
products:ItemList[];

constructor(private productService: ProductService) {}

ngOnInit() {
this.productService.getItems(this.apiUrl)
.subscribe((info:any) => {
 this.products=info;
});
}
}

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

Customizing the entire application's style based on conditions in Angular 4

Looking to implement a dark mode button for the app. Create a toggle switch for "dark mode". This switch will change a boolean value, "dark-ui", between true and false. When the app component detects dark-ui as true, add the class "dark" to a parent-leve ...

What is the process for incorporating a unique Mongo expression into a JSON object?

I'm currently trying to figure out how to add a specific Mongo command to my JSON object. Normally, adding regular strings or objects is straightforward, but I'm struggling with this particular command: $set : { "author" : req.body.name } Simpl ...

Displaying a TypeScript-enabled antd tree component in a React application does not show any information

I attempted to convert the Tree example from antd to utilize TypeScript, however, the child-render function does not seem to return anything. The commented row renders when I remove the comment. The RenderTreeNodes function is executed for each element in ...

A useful Javascript function to wrap a string in <mark> tags within an HTML document

I have a paragraph that I can edit. I need to highlight certain words in this paragraph based on the JSON response I get from another page. Here's an example of the response: HTML: <p id="area" contenteditable> </p> <button class="bt ...

Angular 8 fails to retain data upon page refresh

I have a property called "isAdmin" which is a boolean. It determines whether the user is logged in as an admin or a regular user. I'm using .net core 2.2 for the backend and Postgre for the database. Everything works fine, but when I refresh the page, ...

Navigating the waters of importing npm modules with typescript, gulp, and browserify is a skill

I'm facing challenges with performing some fundamental tasks such as importing packages that I installed using NPM. Despite conducting extensive research online and following various tutorials, I have been unable to achieve success. Here is my current ...

Node.js is having trouble locating the JSON file for Ajax requests

Currently, I've developed a fun little game using the p5.js library and wanted to integrate a Leaderboard feature that pulls data from a JSON file acting as a database to store Usernames and scores. To achieve this, I've utilized a Node.js server ...

Issue with Discord.js (14.1) - Message Handling Unresponsive

After developing a sizable Discord Bot in Python, I decided to expand my skills and start learning JS. Despite thoroughly studying the documentation and comparing with my original Python Bot regarding intents, I am facing difficulties getting the message ...

How Angular services transmit information to components

I have implemented a search field within my top-bar component and I am facing an issue in passing the input value of that search field to another component. Design Search service Top bar component Result component Operation Top bar component receives th ...

Pandas throws an error when trying to convert JSON data to an Excel file

JSON Content: {"user_name":"emma", "user_id":25 } Upon running my Python script, I encountered the following error message: " KeyError: 'index' is missing " I would appreciate any insights on what might be causing this issue in the cod ...

Numerous unspecified generic arguments

Imagine a collection of functions, each capable of taking an argument and returning a value (the specifics don't matter): function convertToNumber(input: string): number { return parseInt(input) } function convertToBoolean(input: number): boolean { ...

Angular 5 offers the ability to incorporate dynamic checkbox input into your application

Here is my code snippet: <input [type]="'checkbox'" [(ngModel)]="inputValue"> <p>Value: {{ inputValue }}</p> I'm puzzled as to why the value in inputValue remains unchanged. Can anyone shed light on this? I am unable to ...

Issue TS2769: No matching overload found for this call. The type 'string | null' cannot be assigned to type 'string | string[]'

export class AuthService { constructor(private http: HttpClient, private webService: WebRequestService, private router: Router) { } login(email: string, password: string) { return this.webService.login(email, password).pipe( shareReplay(), ...

Troubleshooting Paths with Angular's NgFor Directive

Within my Angular project, I have implemented a basic ngFor loop to display logo images. Here is a snippet of the code: <div *ngFor="let item of list" class="logo-wrapper"> <div class="customer-logo"> & ...

Incorporate JavaScript Library into StencilJs Using TypeScript

Recently, I decided to incorporate a JavaScript library called Particles.js into my project. The process involved importing it and initializing it within my component: import { Component, h } from '@stencil/core'; import * as particlesJS from &a ...

In JavaScript, when using the fetch function with JSON, it is possible to skip the

Here's an example of fetching review data from within a 'for loop': fetch('https://api.yotpo.com/products/xx-apikey-xx/{{product.id}}/bottomline') In this case, some products may not have reviews and will return a 404 response. Th ...

Encountering problems during JSON response deserialization

Upon calling an API, I received the following response as part of a functional test for handling a bad query: HTTP/1.1 400 Bad Request Date: Fri, 24 Jan 2014 17:43:39 GMT Sforce-Limit-Info: api-usage=5/5000 Content-Type: application/json;charset=UTF-8 ...

Guide to integrating Gandi.Net API with Node.js in server.js

I'm a beginner in Node.Js and I'm currently working on creating a Mean Stack application. One of the things I need to do is call a 3rd party API, specifically Gandi.Net, from my Node.js code. My Node.Js and Express Application are being used to ...

Transform input string containing newline characters into separate paragraphs

I utilize Contentful CMS for content management and fetch the content through their API. When the content is fetched, it comes in as a JSON object. One of the keys within this object pertains to the main text block for the entry I am retrieving. This stri ...

Transform a group of objects in Typescript into a new object with a modified structure

Struggling to figure out how to modify the return value of reduce without resorting to clunky type assertions. Take this snippet for example: const list: Array<Record<string, string | number>> = [ { resourceName: "a", usage: ...