How to take JSON objects one by one from response object and display in table in Angular?

349 Views Asked by At

The JSON Array get into typescript as response Object from my Java application. I need to pick each object and display into html page corresponding to that typescript page in angular.
list-user.component.ts

import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { Router } from '@angular/router';

@Component({
  selector: 'app-list-user',
  templateUrl: './list-user.component.html',
  styleUrls: ['./list-user.component.css']
})
export class ListUserComponent implements OnInit {
  loginForm!: FormGroup;
  submitted = false;
  jdbc: any;
  username:any

  constructor(private http: HttpClient, private router: Router) { }

  ngOnInit() {
    this.username = JSON.parse(localStorage.getItem("session") || "");
    let listuser: any = {
      username: this.username,
    }
    this.http.post('http://localhost:8080/demoprojectjava/list-user/',
      listuser, { observe: 'response' }).subscribe(res => {
          console.log(res);
  });
  }
}

list-user.component.html

<div>
    <h1 class="listuser"> Display Data from Json File </h1>
    <table>
        <thead>
        <tr>
            <th>User Id</th>
            <th>Lastname</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>{{--Here I need value from Json array}}</td>
            <td>{{--Here I need value from Json array}}</td>
        </tr>
    </tbody>  
    </table>
</div>

When I run my code, in console I got the output as a result for console.log(res); as :

{"user_data":[{"user_id":"111","username":"Hridya"},{"user_id":"222","username":"Rizz"}]}
4

There are 4 best solutions below

0
Hridyadas V D On BEST ANSWER

@Vishnu Prabhu. Thanks for the answer.
Your Typescript code worked smoothly... But I didn't get value with your html code and made a small change. Then I got the values in the table. So I'm posting the entire code that worked well for me, to anyone else for future reference.
list-user.component.ts

import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { Router } from '@angular/router';

@Component({
  selector: 'app-list-user',
  templateUrl: './list-user.component.html',
  styleUrls: ['./list-user.component.css']
})
export class ListUserComponent implements OnInit {
  loginForm!: FormGroup;
  submitted = false;
  jdbc: any;
  username: any;
  data: any;

  constructor(private http: HttpClient, private router: Router) { }

  ngOnInit(): void {
    this.username = JSON.parse(localStorage.getItem("session") || "");
    let listuser: any = {
      username: this.username
    }

    this.http.post('http://localhost:8080/demoprojectjava/list-user/',
      listuser, { observe: 'response' }).subscribe(res => {
        console.log(res.body);
        return this.data = res;
      },
      );
  }
}

list-user.component.html

<div>
    <h1 class="listuser"> Display Data from Json File</h1>
    <table>
        <thead>
            <tr>
                <th>User Id</th>
                <th>Lastname</th>
            </tr>
        </thead>
        <tbody>
            <tr *ngFor="let user of data.body.user_data">
                <td>{{user.user_id}}</td>
                <td>{{user.username}}</td>
            </tr>
        </tbody>
    </table>
</div>
2
Philipp Meissner On

Store the http request as Observable in a property (here userData$). Then use the async pipe in your template to have angular automatically subscribe to it. Then use ngFor to iterate over all the elements inside the response and display the data accordingly.

import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { Router } from '@angular/router';
import { Observable } from 'rxjs';

type ResponseTypeFromYourBackend = any;

@Component({
  selector: 'app-list-user',
  templateUrl: './list-user.component.html',
  styleUrls: ['./list-user.component.css']
})
export class ListUserComponent implements OnInit {
  loginForm!: FormGroup;
  submitted = false;
  jdbc: any;
  username:any
  userData$: Observable<ResponseTypeFromYourBackend>;

  constructor(private http: HttpClient, private router: Router) { }

  ngOnInit() {
    this.username = JSON.parse(localStorage.getItem("session") || "");
    let listuser: any = {
      username: this.username,
    }
    this.userData$ = this.http.post('http://localhost:8080/demoprojectjava/list-user/',
      listuser,
      { observe: 'response' }
    );
  }
}


<div>
  <h1 class="listuser"> Display Data from Json File </h1>
  <table *ngIf="userData$ | async as data">
    <thead>
    <tr>
      <th>User Id</th>
      <th>Lastname</th>
    </tr>
    </thead>
    <tbody>
    <tr *ngFor="let user of data.user_data">
      <td>{{ user.user_id}}</td>
      <td>{{ user.username}}</td>
    </tr>
    </tbody>
  </table>
</div>
0
Fabian Strathaus On

The best way to do this would be to do the following:

  1. Define an observable on class level:
userData$: Observable<YourType>;
...
ngOnInit() {
   ...
   this.userData$ = this.http.post('http://localhost:8080/demoprojectjava/list-user/',
      listuser).pipe(map(item => item.user_data));
  }
  1. Subscribe to this observable using async pipe and iterate over the array:
<tr *ngFor="let item of userData$ | async">
  <td>{{item.user_id}}</td>
  <td>{{item.username}}</td>
</tr>
2
Vishnu Prabhu On

Create a variable to store the response and use ngFor to loop through the array.

import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { Router } from '@angular/router';

@Component({
  selector: 'app-upload-active-census',
  templateUrl: './upload-active-census.component.html',
  styleUrls: ['./upload-active-census.component.css'],
})
export class UploadActiveCensusComponent implements OnInit {
  loginForm!: FormGroup;
  submitted = false;
  jdbc: any;
  username: any;
  data: any;

  constructor(private http: HttpClient, private router: Router) {}

  ngOnInit() {
    this.username = JSON.parse(localStorage.getItem('session') || '');
    let listuser: any = {
      username: this.username,
    };
    this.http
      .post('http://localhost:8080/demoprojectjava/list-user/', listuser, {
        observe: 'response',
      })
      .subscribe((res) => {
        console.log(res);
        return this.data = res;
      });
  }
}
<div>
    <h1 class="listuser"> Display Data from Json File </h1>
    <table>
        <thead>
            <tr>
                <th>User Id</th>
                <th>Lastname</th>
            </tr>
        </thead>
        <tbody>
            <tr *ngFor="let item of data?.user_data">
                <td>{{item.user_id}}</td>
                <td>{{item.username}}</td>
            </tr>
        </tbody>
    </table>
</div>