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

Angular 7中Ag-Grid社区版无法绑定JSON数据求助

解决Angular 7中Ag-Grid无法绑定JSON数据的问题

我仔细看了你的代码和问题描述,很快找到了关键问题,帮你修复:

1. 组件属性访问权限问题

你把rowData声明成了私有(private)属性,但Angular的模板只能访问组件的公共(public)属性,这就导致模板里的[rowData]="rowData"根本无法获取到数据。

只需要把rowData的访问修饰符改成public即可(Angular 7+中如果不声明修饰符默认是public,但显式声明会更清晰):

// 原来的代码
private rowData: any;

// 修改后
public rowData: any;

2. 确认Ag-Grid模块正确导入(关键验证项)

虽然你提到引用配置正确,但还是要确保在你的AppModule里正确导入了AgGridModule,否则组件也无法正常渲染:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { AgGridModule } from 'ag-grid-angular';

import { AppComponent } from './app.component';

@NgModule({
  imports:      [ 
    BrowserModule, 
    HttpClientModule,
    // 导入AgGrid模块
    AgGridModule.withComponents([])
  ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

修改后的完整Component代码

import { Component, ViewChild } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import "ag-grid-community";

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent {
  name = 'Angular';
  private gridApi;
  private gridColumnApi;
  private columnDefs;
  private components;
  // 这里改成public
  public rowData: any;

  constructor(private http: HttpClient) {
    this.columnDefs = [
      { headerName: "Athlete", field: "athlete" },
      { headerName: "Date", field: "date", editable: true, cellEditor: "datePicker" },
      { headerName: "Age", field: "age" },
      { headerName: "Country", field: "country" },
      { headerName: "Year", field: "year" },
      { headerName: "Sport", field: "sport" },
      { headerName: "Gold", field: "gold" },
      { headerName: "Silver", field: "silver" },
      { headerName: "Bronze", field: "bronze" },
      { headerName: "Total", field: "total" }
    ];
  }

  onGridReady(params) {
    this.gridApi = params.api;
    this.gridColumnApi = params.columnApi;
    this.http
      .get(
        "https://raw.githubusercontent.com/ag-grid/ag-grid/master/packages/ag-grid-docs/src/olympicWinnersSmall.json"
      )
      .subscribe(data => {
        this.rowData = data;
      });
  }
}

这样修改后,当HTTP请求返回数据并赋值给rowData时,Ag-Grid就能正常接收到数据并渲染表格了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:34:13