You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中如何从响应对象提取JSON对象并在表格展示

Angular从Java后端获取JSON数组并在表格展示的解决方案

1. 调整TypeScript组件代码,接收并存储后端数据

首先在组件类中新增一个用于存储用户列表的变量,然后在HTTP请求的订阅回调里,从响应对象中提取user_data数组并赋值给该变量。注意因为使用了{ observe: 'response' }配置,返回的res是完整HTTP响应对象,实际业务数据在res.body属性中。

修改后的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;
  // 新增变量存储用户列表数据
  userList: any[] = [];

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

  ngOnInit() {
    // 优化localStorage取值,避免JSON.parse空值报错
    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 => {
        // 提取后端返回的user_data数组
        this.userList = res.body?.user_data || [];
        console.log(this.userList);
      });
  }
}

2. 修改HTML模板,循环渲染表格数据

在表格的<tbody>中使用Angular的*ngFor指令遍历userList变量,动态生成每一行数据。另外注意原表头的"Lastname"与后端返回的username字段不匹配,这里统一调整表头为"Username"(如果实际需要展示Lastname,请确认后端是否返回对应字段)。

修改后的list-user.component.html代码:

<div>
    <h1 class="listuser"> Display Data from Json File </h1>
    <table>
        <thead>
        <tr>
            <th>User Id</th>
            <th>Username</th>
        </tr>
    </thead>
    <tbody>
        <!-- 遍历userList生成每一行数据 -->
        <tr *ngFor="let user of userList">
            <td>{{user.user_id}}</td>
            <td>{{user.username}}</td>
        </tr>
    </tbody>  
    </table>
</div>

内容的提问来源于stack exchange,提问作者Hridyadas V D

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 19:10:32