Tips for presenting a table of data retrieved from an API in an Angular 7 application using HTML

While working on an Angular 7 application, I encountered an issue where I was trying to fetch tabular data from an API call and assign it to HTML elements. Below is the code snippet I used:

Typescript class:

export class IBiodatas{
    CompanyId:number;
    EmpCode: string;
    ImageURL: string;
    Name: string;
    UserId : number;
}

Typescript service call :

getDetail(userName):Observable<IBiodatas[]>{
  return this.http.get<IBiodatas[]>(this.API_URL + userName,this.httpOptions).pipe(
    catchError(this.handleError('getDetail',[]))
  )
}

Typescript component code :

heroes: IBiodatas[];

getDetail(): void {
    this.biodataService.getDetail('?userName=Santosh')
      .subscribe(      
        data=> {
          this.heroes = Array.of(data.data.Table[0]);//Error: Property 'data' does not exist on type 'IBiodatas[]'.
          console.log('456456',this.heroes);
        },
      );
  }

Received data from API :

{
"APIExecutionTime":"0 sec(s) to execute the function",
"data":{
    "Table":[{
    "UserId":654,
    "ImageURL":"654.png",
    "Name":"Santosh Pal",
    "CompanyId":78,"EmpCode":"987"
    }]},
"httpStatusCode":200,
"msg":"OK",
"IsValid":true
}
how to get data.Table[0] and assign to class property

ERROR in src/app/app.component.ts(30,41): error TS2339: Property 'data' does not exist on type 'IBiodatas[]'.

Answer №1

fetchInfo(){

this.infoService.fetchInfo('?username=Santosh').subscribe(data =>{
    this.usersList = Array.of(data)
    this.userDetails = Array.of(this.usersList[0].info.Table[0]);
});

}

Answer №2

If you want to display data in a table, you can use the following approach:

<table>
   <tr>
      <th>User ID</th>
      <th>Name</th>
   </tr>
   <tr *ngFor="let item of items">
      <td>{{item.userId}}</td>
      <td>{{item.name}}</td>
   </tr>
</table>

Answer №3

Give this a shot:

Try using JSON.stringify(res) for <code>this.data
instead of simply assigning res.data.table.

<table>
   <tr>
      <th>UserId</th>
      <th>Name</th>
   </tr>
   <tr *ngFor="let d of data">
      <td>{{d.UserId}}</td>
      <td>{{d.Name}}</td>
   </tr>
</table>

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

Angular 2: Triggering functions on click within a dynamic template (dynamic component)

Here is an example to demonstrate how to create dynamic templates and compile dynamic components in Angular 2.0: How can I use/create dynamic template to compile dynamic Component with Angular 2.0? I have built my own template generator that fetches HTML ...

Steer clear of using inline styling when designing with Mui V5

I firmly believe that separating styling from code enhances the clarity and cleanliness of the code. Personally, I have always viewed using inline styling (style={{}}) as a bad practice. In Mui V4, it was simple - I would create a styles file and import i ...

The completion of RxJS forkJoin is not guaranteed

After subscribing to getAllSubModules, forkJoin executes all the observables without any errors but fails to complete. Even though forkJoin should only complete after all its observables have completed, I'm seeing '-----' printed 3 times in ...

What is the reason for using 'Input' as a type instead of referring to it as a value? TS 2749

The file format is correct as .tsx, however, there seems to be an issue with using HTMLInputElement instead of Input. In my opinion, it should be Input since it relates to the assigned value. Can you help identify the problem in the code snippet below at l ...

Is it possible to preserve the spoken "text" through Ionic Speech Recognition for future reference?

After successfully implementing Ionic Speech Recognition in my project using the Ionic framework documentation, I am now facing a challenge with saving the text or audio input using any form input method like ngmodel or formcontrol. My attempts to bind th ...

Encountering a CORS issue when utilizing passport-facebook for Facebook authentication in my MEAN application

I'm currently working on implementing a Facebook login feature for my web app, built with express js, mongodb, and angular 2. The client-side of the app is generated using angular-cli (running on port 4200), and I'm utilizing the proxy config pr ...

Execute the CountUp function when the element becomes visible

Currently, I am implementing the following library: https://github.com/inorganik/ngx-countUp Is there a way to activate the counting animation only when the section of numbers is reached? In other words, can the count be triggered (<h1 [countUp]="345 ...

Is it possible for an object's property specified in a TypeScript interface to also incorporate the interface within its own declaration?

While it may seem like an unusual request, in my specific scenario, it would be a perfect fit. I am working with an object named layer that looks something like this: const layer = { Title: 'parent title', Name: 'parent name', ...

Unit testing in Angular 4 with Jasmine Spy: The expectation was for 'New text' but received undefined

I have a simple function in my app.component.ts that is meant to modify a parameter, and I am trying to test this function using a spy. However, for some reason, my changeText function always returns undefined. Can you help me identify what I might be doin ...

Creating generic output types in TypeScript based on the input types

In my React-Native project, I'm focusing on implementing autocomplete and type validation. One of the challenges I'm facing is configuring the types for the stylesheet library I am using. A customized stylesheet is structured like this: const s ...

Retrieve information from Firebase outside of the .on() method

As a newcomer to Typescript, I am struggling to understand how to access the variables latitude1 and latitude2 outside of the this.ref.on('value', (snapshot) function in order to add their values to the locations array. Can anyone provide some gu ...

Encountering the Selenium Webdriver HTTP error within an Angular 4 project

ERROR Detected Issue found in: ./node_modules/selenium-webdriver/http/index.js Module not found: Error: Unable to locate 'http' in 'C:\Users\aprajita.singh\Documents\Angular 4\Auto-Trender-Project\node_modules ...

Ways to transfer information from the parent component while the component is repeatedly utilized on the page

Consider the following situation within Angular 6: There is one upload component that is being utilized twice on the same page. By clicking the add button on any upload component using a behavior subject, data specific to that upload component can be obt ...

Guide to configuring an Angular Material Footer using Flex-Layout

Could someone help me with setting up the footer in my Angular Material app? I want it to: stick to the bottom when the content height is smaller than the view-port move down or get pushed down when the content height exceeds the view-port One important ...

unable to reinstall due to removal of global typing

After globally installing Moment typing with the command typings install dt~moment --save --global Checking the installed typings using typings list shows: ├── <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="93fffcf7f2e0 ...

I'm having trouble with ViewChild - consider upgrading to beta7 for a solution

import {Page,NavController,NavParams,Platform,IonicApp} from 'ionic-angular'; import {ViewChild} from '@angular/core'; @Page({ templateUrl: 'build/pages/tabspage/tabspage.html' }) @ViewChild('myTabs') tabRef: T ...

Tips on obtaining a unique value that does not already exist in a specific property within an Array of objects

I am faced with a challenge involving an array that contains objects with both source and target properties. My goal is to identify a value that never appears as a target. My current approach seems convoluted. I separate the elements of the array into two ...

Angular 2+ encountering an internal server error (500) while executing an http.post request

Here is my service function: public postDetails(Details): Observable<any> { let cpHeaders = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: cpHeaders }); return this.htt ...

Validating dynamic forms with multiple rows in Angular 9

I am looking for a way to consolidate validation errors in one place for multiple rows created dynamically based on user input. Instead of displaying the error message next to each field, I want all the validation errors for each row to be displayed collec ...

How to link observables in HTTP requests using Angular 5?

I'm currently developing an application using Angular 5, and I want to segregate raw http calls into their own services so that other services can modify the responses as needed. This involves having a component, component service, and component data ...