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

Angular/TypeScript新手求助:ag-grid无法显示JSON加载的数据

Troubleshooting ag-Grid Data Not Showing in Angular/TypeScript

Hey there! I’ve been where you are—struggling with Angular and ag-Grid when everything compiles but the data just refuses to show up. Let’s break down the most likely issues across your files and fix this step by step:

1. Check Your Data Service (my-grid-application.service.ts)

First, let’s make sure your service is actually loading the JSON data correctly:

  • Local JSON path & HttpClient setup: Angular requires local JSON files to be in the assets folder (or configured in angular.json under the assets array) to be accessible. Your service should use HttpClient to fetch it, like this:
    import { HttpClient } from '@angular/common/http';
    import { Injectable } from '@angular/core';
    import { Observable } from 'rxjs';
    
    @Injectable({ providedIn: 'root' })
    export class MyGridApplicationService {
      constructor(private http: HttpClient) {}
    
      getData(): Observable<any[]> {
        // Make sure the path matches where your data.json lives
        return this.http.get<any[]>('/assets/data.json');
      }
    }
    
  • Don’t forget to subscribe! If you call getData() in your component but never subscribe to the Observable, the data will never load. Subscribing triggers the HTTP request.

2. Verify Component Data Binding (my-grid-application.component.ts)

Your component needs to correctly handle the data and pass it to ag-Grid:

  • Initialize rowData and columnDefs: Ensure rowData is an array, and your columnDefs match the fields in your JSON data. For example:
    import { Component, OnInit } from '@angular/core';
    import { MyGridApplicationService } from './my-grid-application.service';
    
    @Component({
      selector: 'app-my-grid',
      templateUrl: './my-grid-application.component.html'
    })
    export class MyGridApplicationComponent implements OnInit {
      rowData: any[] = [];
      // Match these fields exactly to your JSON properties
      columnDefs = [
        { field: 'id', headerName: 'ID' },
        { field: 'name', headerName: 'Name' },
        { field: 'email', headerName: 'Email' }
      ];
    
      constructor(private gridService: MyGridApplicationService) {}
    
      ngOnInit(): void {
        this.gridService.getData().subscribe({
          next: (data) => {
            this.rowData = data;
            // Add a console log here to confirm data is loaded
            console.log('Loaded data:', data);
          },
          error: (err) => console.error('Failed to load data:', err)
        });
      }
    }
    
  • Check ag-Grid module imports: Make sure you’ve imported AgGridModule in your component’s module (e.g., AppModule) and added it to the imports array:
    import { AgGridModule } from 'ag-grid-angular';
    
    @NgModule({
      imports: [AgGridModule.withComponents([]), ...],
      ...
    })
    export class AppModule {}
    

3. Validate Your data.json File

ag-Grid expects rowData to be an array of objects—double-check your JSON format:

  • Valid array format: Your JSON should look like this (not a single object wrapping an array, unless you handle that in the component):
    [
      { "id": 1, "name": "Alice Smith", "email": "alice@example.com" },
      { "id": 2, "name": "Bob Johnson", "email": "bob@example.com" }
    ]
    
  • If your JSON has a wrapper object: If your data is nested (e.g., { "users": [...] }), update your subscription to extract the array:
    this.gridService.getData().subscribe(data => {
      this.rowData = data.users; // Grab the array from the wrapper
    });
    

4. Fix the Grid Template (my-grid-application.component.html)

Make sure your ag-Grid component is set up correctly in the template:

  • Bind rowData and columnDefs properly: Use square brackets for property binding:
    <ag-grid-angular
      style="width: 100%; height: 500px;"
      class="ag-theme-alpine" <!-- Don't skip the theme! -->
      [rowData]="rowData"
      [columnDefs]="columnDefs"
    ></ag-grid-angular>
    
  • Add a theme class: Without a theme class like ag-theme-alpine, the grid might be invisible (even if data is loaded). This is a super common gotcha!
  • Debug with grid events: Add a gridReady event to confirm the grid is initialized:
    <ag-grid-angular
      ...
      (gridReady)="onGridReady($event)"
    ></ag-grid-angular>
    
    Then in your component:
    onGridReady(params: any) {
      console.log('Grid is ready!');
      // You can also check rowData here: console.log(params.api.getRowCount());
    }
    

Quick Debugging Tips

  • Open your browser’s DevTools Console: Look for HTTP errors (like 404 for data.json) or TypeScript errors that didn’t show up in compilation.
  • Log the data in your component’s subscription: This confirms if the data is actually being fetched.
  • Use Angular DevTools: Inspect your component to see if rowData has values assigned.

Hopefully one of these fixes gets your data showing up in the grid!

内容的提问来源于stack exchange,提问作者Vasco Oliveira

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 10:34:41