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

Angular 16从API获取的数据无法显示问题求助

问题分析与修复方案

1. API 请求 URL 格式错误

你的 apiUrl 已包含查询参数(?size=50&is_json=true),但在 getData 方法中再次用 ? 拼接分页参数,导致 URL 格式无效。需改用 & 追加新参数。

修复后 api.service.ts:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ApiService {
  private apiUrl = 'https://random-data-api.com/api/v2/users';

  constructor(private http: HttpClient) { }

  getData(pageSize: number): Observable<any[]> {
    // 注意:该API不支持page参数,仅通过size指定返回数量
    const url = `${this.apiUrl}?size=${pageSize}&is_json=true`;
    return this.http.get<any[]>(url);
  }
}

2. API 不支持服务端分页

random-data-api.com 的 /api/v2/users 接口没有 page 和 pageSize 分页参数,仅通过 size 返回指定数量的随机用户。若需真实分页效果,要么预先获取全量数据做客户端分页,要么更换支持服务端分页的 API。

3. 数据赋值逻辑错误

loadData 方法中错误将 data.totalItems 赋值给 dataSource,但 API 返回的是用户数组,不存在 totalItems 属性。同时 totalItems 需手动设置为总数据量(比如预设的50条)。

修复后 data-table.component.ts:

import { Component, OnInit } from '@angular/core';
import { ApiService } from '../api.service';

@Component({
  selector: 'app-data-table',
  templateUrl: './data-table.component.html',
  styleUrls: ['./data-table.component.css']
})
export class DataTableComponent implements OnInit {
  displayedColumns: string[] = ['id', 'name', 'email'];
  dataSource: any[] = [];
  pageSize = 10;
  currentPage = 0; // MatPaginator的pageIndex从0开始,无需额外+1
  totalItems = 50; // 预设总数据量

  constructor(private apiservice: ApiService) {}

  ngOnInit(): void {
    this.loadData();
  }

  loadData(): void {
    this.apiservice.getData(this.pageSize).subscribe((data: any[]) => {
      this.dataSource = data; // 直接赋值用户数组
    });
  }

  onPageChange(event: any): void {
    this.currentPage = event.pageIndex;
    this.pageSize = event.pageSize;
    this.loadData();
  }
}

4. 模板与分页参数对齐

修正 mat-paginator 的 pageIndex 绑定,同时调整姓名列的显示字段(API返回的是first_name和last_name,而非name):

修复后 data-table.component.html:

<table mat-table [dataSource]="dataSource">
    <ng-container matColumnDef="id">
        <th mat-header-cell *matHeaderCellDef>ID</th>
        <td mat-cell *matCellDef="let item">{{item.id}}</td>
    </ng-container>

    <ng-container matColumnDef="name">
        <th mat-header-cell *matHeaderCellDef>姓名</th>
        <td mat-cell *matCellDef="let item">{{item.first_name}} {{item.last_name}}</td>
    </ng-container>

    <ng-container matColumnDef="email">
        <th mat-header-cell *matHeaderCellDef>邮箱</th>
        <td mat-cell *matCellDef="let item">{{item.email}}</td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>

</table>

<mat-paginator
    [length]="totalItems"
    [pageSize]="pageSize"
    [pageIndex]="currentPage"
    [pageSizeOptions]="[10, 20, 30]"
    (page)="onPageChange($event)" 
></mat-paginator>

5. 模块配置优化

AppModule 中无需将 HttpClientModule 添加到 providers 数组,已在 imports 中导入:

修复后 AppModule:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { MatPaginatorModule } from '@angular/material/paginator';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { DataTableComponent } from './data-table/data-table.component';
import { MatTableModule } from '@angular/material/table';
import { HttpClientModule } from '@angular/common/http';


@NgModule({
  declarations: [
    AppComponent,
    DataTableComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    MatPaginatorModule,
    MatTableModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }

内容的提问来源于stack exchange,提问作者Adebakin Yusuf

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 17:00:58