我的ag-grid没有显示任何数据

时间:2018-02-27 15:22:07

标签: javascript json angular ag-grid

我是Angular / Typescript的新手。我有点学习和发展的同时。我正在尝试使用从Json文件加载的数据构建网格,并且我在显示我的数据时遇到了一些问题。我很乐意,如果你们可以指出我的错误,因为我的代码编译没有错误,而且我现在有点无助。

我在下面提供我的代码。 提前谢谢。

我的并网application.component.ts

@Component({
  selector: 'app-my-grid-application',
  templateUrl: './my-grid-application.component.html'
})
export class MyGridApplicationComponent {
  private gridOptions: GridOptions;
  things:Things[];

  getThings(){
    this.myGridApplicationService.getThings().subscribe( things => 
this.things = things)
  }

constructor( private myGridApplicationService: MyGridApplicationService) {
    this.gridOptions = <GridOptions>{};
    var gridOptions = {
        onGridReady: function() {
    this.gridOptions.api.setRowData(this.things);
        }
    }
    this.gridOptions.columnDefs = [
        {
            headerName: "ID",
            field: "id",
            width: 100
        },
        {
            headerName: "Value",
            field: "value",
            cellRendererFramework: RedComponentComponent,
            width: 100
        },

    ]; 
  } 
}

我的并网application.service.ts

export class Things{

}

@Injectable()
export class MyGridApplicationService {
  constructor(private http: Http){ }

  getThings(){
    return this.http.get('src/assets/data.json')
        .map((response:Response)=> <Things[]>response.json().data)
  }
}

data.json

{
"data" :[
    {
        "id": "red",
        "value": "#f00"
    },
    {
        "id": "green",
        "value": "#0f0"
    }
]
}

我的并网application.component.html

<div style="width: 200px;">
  <ag-grid-angular #agGrid style="width: 100%; height: 200px;" class="ag-
theme-fresh"
           [gridOptions]="gridOptions">

   

2 个答案:

答案 0 :(得分:1)

我不是Ag-Grid专家,但为什么要在构造函数中使用 var gridOptions 重新声明gridOptions。这是一个明显的错误,应予以纠正:

this.gridOptions = {
    onGridReady: function() {
        this.gridOptions.api.setRowData(this.things);
    }
}

因为这是您在模板中访问的属性。

从我的StackBlitz

中查看Github
//MyGridApplication
constructor( private myGridApplicationService: MyGridApplicationService) {
    myGridApplicationService.getThings()
        .subscribe( things => this.things = things);

    this.gridOptions = <GridOptions>{};
    this.gridOptions = {
        onGridReady: () => {
            this.gridOptions.api.setRowData(this.things);
        }
    };

    this.gridOptions.columnDefs = [
        {
            headerName: "ID",
            field: "id",
            width: 100
        },
        {
            headerName: "Value",
            field: "value",
            cellRendererFramework: RedComponentComponent,
            width: 100
        },

    ]; 
} 

答案 1 :(得分:0)

当触发onGridReady()时,尚未填充“this.things”。 试试这个:

var gridOptions = {
    rowData: this.things
}