Struggling to convert a JSON array into a dynamic HTML table in Angular using TypeScript, resulting in a blank output

After researching extensively, I have attempted various methods to incorporate dynamic data into an HTML file. Unfortunately, none of them seem to be working for me at the moment.

In my app.component.html file, I inserted the following lines. While I can see the headers on the HTML page, the values are not appearing and I do not encounter any error messages in the Chrome console.

app.component.html:

<table width="100%" class="table">
  <thead>
     <tr>
      <th> Product Name</th>
      <th> API Name </th>
      <th>Message</th>
     </tr>
  </thead>
  <tbody>
     <tr *ngFor="let binary of data">
       <td>{{binary.productName}}</td>
       <td>{{binary.apiName}}</td>
       <td>{{binary.message}}</td>
     </tr>
  </tbody>
   </table>

app.component.ts:

 getById():void {
    const url:any = "http://localhost:8081/api/products?productId=23421342221";       
    this.http.get(url).subscribe(data =>{ 
        console.log(data);
    });  
  }

The code above correctly displays values in the console as shown below:

https://i.sstatic.net/v8tNS.png

This is a sample JSON Array representation (Dummy JSON model):

{
 "dataSet":[
            { 
              "productName": "mobile", 
              "apiName":"Android",
              "message":"Its android mobile device and model is sony m5"
            },
            {
              "productName": "Laptop", 
              "apiName":"Linux",
              "message":"It's linux OS and kernel version is <XXX>"
            }
         ]
 }

I am seeking assistance in identifying what may be missing in my code or why it is not displaying properly. Understanding the logic behind this issue will be greatly beneficial for future reference.

Thank you in advance for your help.

Answer №1

To retrieve the dataSet array from the data object, you must modify your code like so:

Update your code to:

this.api.get(url).subscribe(response =>{ 
       this.data = response.dataSet;
}); 

Answer №2

To adopt good coding practices, consider utilizing the async pipe to subscribe to observables directly from the template. Here is a simple example:

data$: Observable<any[]>;
ngOnInit(): void {
   this.data = this.http.get<any[]>(url).pipe(map(json => json.dataSet));
}

     <tr *ngFor="let binary of data$ | async">
       <td>{{binary.productName}}</td>
       <td>{{binary.apiName}}</td>
       <td>{{binary.message}}</td>
     </tr>

By following this approach, you can avoid the hassle of manually unsubscribing from hot observables or dealing with initial state concerns.

Answer №3

Here's a sample code snippet:

Make sure to declare the data property as an array.

public data: Array<any> = [];

public fetchDataById():void {
    const url:any = "http://localhost:8081/api/products?productId=23421342221";       
    this.http.get(url).subscribe((data:any)=>{ 
        this.data = data.dataSet;
    });  
  }

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

Retrieve the md-sidenav-layout element within a TypeScript file component

Using md-sidenav in my application has been quite useful. Assigning an object to md-sidenav involves the following syntax: <md-sidenav #start With this syntax, "start" will hold all variables and methods of md-sidenav, allowing for operations such ...

How can I upload multiple images in one request using Typescript?

HTML: <div> <input type ="file" (change)="selectFiles($event)" multiple="multiple" /> </div> Function to handle the change event selectFiles(event) { const reader = new FileReader(); if (event.target.files & ...

What is the reason behind TypeScript permitting the assignment of a class instance to a variable that is of a different type?

When examining the given code, it raises a question about why the TypeScript compiler permits the assignment const c1: I = new C();. The issue arises when the function call c1.z(args); results in an error due to the absence of the first property in the a ...

Tips for implementing an 'exclude' feature in TypeScript without encountering any error notifications

export function omit<T, U extends keyof T>(obj: T, keys: U[]): Omit<T, U> { return Object.keys(obj).reduce( (acc, curr) => (keys.includes(curr as U) ? acc : { ...acc, [curr]: obj[curr] }), {} ) as Omit<T, U>; } Encounter ...

How can I compel npm to resolve dependencies flatly?

I am working on a project where multiple frontends share a common library. The module dependencies for these projects are managed using npm. In the package.json file of each project, I specify: "dependencies": { "mylib": "file:../<...path...> ...

The Raycaster fails to identify objects that have been rotated

I have recently started working with Three.js and I'm facing an issue with raycasting not detecting certain parts of a rotated mesh object. For instance, in the image below, when the mouse is at the position of the green circle, it's detected as ...

A method for enabling mat-spinner's entrance animation

I have recently implemented an Angular Material spinner with a disappearing animation that moves downwards before fading away. Is there a way to disable this animation? I have already tried using keyframes without success. <mat-spinner style="margin: ...

How can I correctly enable the css property in Emotion 11 and Next.js 10 applications?

The css property is not being detected during the build process. It's unclear whether this issue stems from a misconfiguration in the project settings or if it's a known bug. Type '{ children: (string | number | boolean | {} | ReactElement ...

When no values are passed to props in Vue.js, set them to empty

So I have a discount interface set up like this: export interface Discount { id: number name: string type: string } In my Vue.js app, I am using it on my prop in the following way: export default class DiscountsEdit extends Vue { @Prop({ d ...

How can I alter the appearance of HTML text when hovering over the enclosing div?

I want the text to change color and zoom when the cursor is near it (when the mouse enters the area of the div containing the text). Currently, I am able to change the text color only when hovering directly over it. Below is a snippet of the code. HTML: & ...

What is the proper way to combine two arrays containing objects together?

I am faced with the challenge of merging arrays and objects. Here is an example array I am working with: [ { name: "test", sub: { name: "asdf", sub: {} } }, { name: "models", sub: {} } ] ...

Challenges with Angular 2 navigation paths

I'm currently facing a routing issue in my Angular 2 project. The app is quite small, featuring a PageNotFoundComponent, a HomeComponent for the index page, and an admin section. The admin section consists of a main AdminComponent, an AdminDashboardC ...

Top Choice UI Component for Angular 2 Development

As a newcomer to Angular2, I am in the process of building an application from scratch. This application will require extensive use of controls such as Scheduler, Grids, Charts, and others. After researching on Google, I have come across Syncfusion, Kend ...

What is preventing me from sorting multiple times?

My current challenge involves sorting an array of data multiple times for different purposes. While I could choose to save the sorted data on the back end, I prefer handling it this way. However, I have encountered a problem where only one sort operation ...

A guide to handling state in Angular with the help of services and BehaviorSubjects

I am currently unfamiliar with NgRx and I am seeking guidance on managing state in an Angular application. The app is relatively straightforward - we have a list of items that are downloaded and displayed when the user accesses the item list. However, if ...

invoking an API within a map function and utilizing the response

vm.owners = parents.children.map(function(e) { getparentById(e.Id) .then(function(getresponse) { var parentLink = '<a href="/#/parent/onboard/' + e.Id + '" target="_blank">' + e.Number + "-&qu ...

Expanding the capabilities of the Express Request Object using TypeScript

Looking to enhance the Request object of express with a new property To start, create a middleware that verifies the session and token containing the companyId import { verifyToken } from '../utils/jwt/jwt'; declare module 'express-serve-s ...

Tips for selecting specific regions on an Angular SVG map

For my Angular TypeScript project, I included a map. Does anyone know how to create a select region on the map? Click here for StackBlitz Here is the jsFiddle code link CSS styles here p { font-size: 12px; } #core { fill: #ff4f81; animatio ...

Dealing with HTTP Client Errors in Service Operations

In my app, I've implemented a shared authentication service to handle all authentication tasks. I am currently working on abstracting the component logic as much as possible from the HTTP requests. However, most of the documentation I've come acr ...

How to Use Exceljs to Extract Date Data in Specific Cell Formatting

While working on a project using Nest, I encountered an issue when reading a Date value from columns in an excel file using the exceljs package. Instead of getting the Date data type in the correct format, I am receiving a number as the output. Here is th ...