0

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 Answers 4

1

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>
Sign up to request clarification or add additional context in comments.

2 Comments

Wow, astonishing how similar our answers are :D Guess this can really be seen as a best practice then :D
Yes, I really like that you re-mapped user_data outside the template already. Good job :)
1

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>

Comments

1

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>

2 Comments

This will cause a runtime error the moment data.user_data gets evaluated before the request was finished.
@Vishnu Prabhu. Your Typescript code worked smoothly... But I didn't got value with your html code and made a small change as <tr *ngFor="let user of data.body.user_data"> . Then I got the values in table
0

@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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.