AgGrid / Angular 2:无法访问setRowData()。网格渲染,不显示rowData

时间:2018-04-10 08:32:21

标签: javascript angular ag-grid

解决(有点) 我相信我的解决方案很简单,并且表明我不正确地设置了我的猫鼬模型。

下面的答案确实帮我解决了我的问题,所以我检查了一下,但最后空白数据行的原因是属性中的标识符不正确

即。在my-gridcomponent-name.component.ts

gridOptions.columnDef.field 

我需要使用实际的数据库字段名称/标识符设置字段属性。

我使用的是我在mongoose Schema中指定的名称/标识符,而不是数据库的实际字段名称/标识符。例如,Schema标识符,其中所有单词小写,而数据库标识符以大写开头,并且可能在单词之间具有_。

问题从这里开始......

我从MongoDB获取一组JSON对象,并希望在agGrid中显示它们。

$ng version angular-cli: 1.0.0-beta.28.3 node: 6.9.2 os: win32 x64 
@angular/common: 2.4.10 
@angular/compiler: 2.4.10 
@angular/core: 2.4.10 
@angular/forms: 2.4.10 
@angular/http: 2.4.10 
@angular/platform-browser: 2.4.10 
@angular/platform-browser-dynamic: 2.4.10 
@angular/router: 3.4.10 
@angular/compiler-cli: 2.4.10

我99%肯定我有数据在数组中,它可用于我的HTML页面。

1)console.log(Array.isArray(self.catalogue)) //true

2)我在*ngFor标记下面测试了<ag-grid-angular>。有效。

<div *ngFor='let note of catalogue'> 
    <li>{{note.Country}}</li> 
    <li>{{note.Authority}}</li> ......etc 
</div>

这篇文章的截图显示了我的agGrid基本上是什么样子 - 它有标题和滚动条,好像数据是用隐形墨水打印的。 UI Grid Angular, grid renders but doesn't display data

如果我只是在构造函数中对某些对象进行硬编码,那么将显示rowData。

constructor(private catalogueService: CatalogueService) {
 this.gridOptions = <GridOptions>{},
 this.gridOptions.columnDefs = [
 {
  headerName: "Country",
  field: "country",
  width: 200
},.....
]    
this.gridOptions.rowData = [
  {country: 'pig', authority: 'A12', banknoteID: 'bn1', pickID: 'p1', currency: 'thalers', denomination: 10},   
  ]
}

这是我的.html文件

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

我的.ts文件

import { Component, OnInit } from '@angular/core';
import { CatalogueService } from '../services/catalogue.service';
import { Catalogue } from '../models/Catalogue';
import { GridOptions } from 'ag-grid';

@Component({
  selector: 'app-ag-grid-catalogue',
  templateUrl: './ag-grid-catalogue.component.html',
  styleUrls: ['./ag-grid-catalogue.component.css']
})

export class AgGridCatalogueComponent implements OnInit {

private gridOptions: GridOptions;
private catalogue: Catalogue [];

constructor(private catalogueService: CatalogueService) {
   this.gridOptions = <GridOptions>{},
   this.gridOptions.columnDefs = [
    {
      headerName: "Country",
      field: "country",
      width: 200
    },....etc
  ]

   this.gridOptions.rowData = [ ]
  }
 //Methods
 loadCatalogue () {
   //Assign this to self to be used in callbacks
   var self = this;
     return this.catalogueService.getCatalogue().subscribe(function (data) {
        //Why can't I use dot notation to access the data param?
        //console.log(data) ==> {success: true, catalogue: Array(4)}
        if (data['success']) {
        //Bind "catalogue" to the [rowData] in the <ag-grid-angular> tag
        self.catalogue = data['catalogue']
        // tried and failed:self.gridOptions.rowData = data['catalogue'];          
        // return data['catalogue'];
       };
     })
    };

    ngOnInit () {
       this.loadCatalogue();
    };
   } 

这是服务,但似乎我得到了一系列JSON对象,所以我不认为问题在服务中

import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { Observable } from 'rxjs/Observable';

import 'rxjs/add/operator/map';

@Injectable()
export class CatalogueService {

constructor(private http: Http) { }

private serverApi= 'http://localhost:3000';

public getCatalogue():Observable <Object> {
  // let headers = new Headers();
  // headers.append('Content-type', 'application/json');
  let URI = `${this.serverApi}` + `/`;
    return this.http.get(URI)
      .map(function (res) {
         return res.json();
      });
    }
  }
  

_______________________________________________________________________

     

======================根据Dermo的建议更新============== ======   的 _______________________________________________________________________

我仍然无法访问setRowData方法。

进行调整并添加自己后。到你的代码的一行,

self.gridApi.setRowData(self.catalogue);

浏览器中的控制台显示:

// error_handler.js:54 EXCEPTION:无法读取属性&#39; setRowData&#39;未定义的

交换以上代码行:

self.gridOptions.api.setRowData(self.catalogue)

ng serve compiles并且浏览器控制台中没有错误,但是...... 行数据仍未显示。

注意,在this.gridOptions.rowData = [{blah,blah,...]}中使用硬编码数组,网格呈现硬编码数据,但很快就会删除数据并且网格都是空行

看来我的gridOptions对象和gridApi对象都没有setRowData方法。单击浏览器控制台中显示的对象时,我应该看到该方法吗?我没有看到您链接的api.docs中详述的任何方法。

  

_______________________________________________________________________

以下是一些更多细节(希望相关。)

在更改任何代码之前,我使用

中的console.log运行程序
loadCatalogue () {
//Assign this to self to be used in callbacks
var self = this;

return this.catalogueService.getCatalogue().subscribe(function (data) {
  if (data['success']) {        
      self.catalogue = data['catalogue']
      console.log('in cb', self)
    };
  })
};

console.log(self):
AgGridCatalogueComponent {catalogueService: CatalogueService, gridOptions: {…}, catalogue: Array(15)}
catalogue:        (15) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
catalogueService: CatalogueService {http: Http, serverApi: "http://localhost:3000"}
gridOptions:      { columnDefs: Array(11), 
                    rowData: Array(15), //(has the array of JSON objects I expected!)
                    api: GridApi,   //(with a list of properties/methods - as stated in the origainal question there is NO setRowData method)
                    columnApi: ColumnApi
                  }
__proto__:    Object

所以,就像你说的那样,问题似乎是.html上的网格在为rowData属性赋值之前呈现。

根据您的建议,我将4个项目添加到该计划中:

in .html

(gridReady)="onGridReady($event)"

in .ts

private gridApi;

gridApi.setRowData(self.catalogue);

onGridReady(params) {
  this.gridApi = params.api;
};
  

$ ng serve   不编译://无法找到名称&#39; gridApi&#39;在.ts

解决方案:

self.gridApi.setRowData(self.catalogue);  //Added the self. to the line of code

$ ng服务现在编译,但是......

浏览器中的

控制台读取 //error_handler.js:54 EXCEPTION:无法读取属性&#39; setRowData&#39;未定义的

console.log(self):
Has one additional property: (due to the onGridReady(params) {this.gridApi = params.api;};????

gridApi:    GridApi {detailGridInfoMap: {…}, immutableService: ImmutableService, csvCreator: CsvCreator, excelCreator: null, gridCore: GridCore, …}

1 个答案:

答案 0 :(得分:0)

问题是ag-grid已使用空数组初始化。你可以通过多种方式解决这个问题。

  • 一种选择是在加载目录数据之前检索目录数据 组件。
  • 下面详述的第二个选项是使用ag-grid api来设置/更新
    网格数据。

首先,更新模板以绑定到gridReady事件

<div style="width: 1000px;">
  <ag-grid-angular #agGrid style="width: 100%; height: 200px;" 
    class="ag-fresh"
    [gridOptions]="gridOptions"
    [rowData]="catalogue"
    (gridReady)="onGridReady($event)">
  </ag-grid-angular>
</div>

现在将onGridReady函数添加到.ts并添加对grid api的引用。然后在loadCatalogue

中设置数据行
import { Component, OnInit } from '@angular/core';
import { CatalogueService } from '../services/catalogue.service';
import { Catalogue } from '../models/Catalogue';
import { GridOptions } from 'ag-grid';

@Component({
  selector: 'app-ag-grid-catalogue',
  templateUrl: './ag-grid-catalogue.component.html',
  styleUrls: ['./ag-grid-catalogue.component.css']
})

export class AgGridCatalogueComponent implements OnInit {

private gridOptions: GridOptions;
private catalogue: Catalogue [];
private gridApi;

constructor(private catalogueService: CatalogueService) {
   this.gridOptions = <GridOptions>{},
   this.gridOptions.columnDefs = [
    {
      headerName: "Country",
      field: "country",
      width: 200
    },....etc
  ]

   this.gridOptions.rowData = [ ]
  }
 //Methods
 loadCatalogue () {
   //Assign this to self to be used in callbacks
   var self = this;
     return this.catalogueService.getCatalogue().subscribe(function (data) {
        //Why can't I use dot notation to access the data param?
        //console.log(data) ==> {success: true, catalogue: Array(4)}
        if (data['success']) {
        //Bind "catalogue" to the [rowData] in the <ag-grid-angular> tag
        self.catalogue = data['catalogue'];
        gridApi.setRowData(self.catalogue);
        // tried and failed:self.gridOptions.rowData = data['catalogue'];          
        // return data['catalogue'];
       };
     })
    };

    ngOnInit () {
       this.loadCatalogue();
    };

    onGridReady(params) {
      this.gridApi = params.api;
    };
   }

更新网格数据:https://www.ag-grid.com/javascript-grid-data-update/

访问api / data:https://www.ag-grid.com/javascript-grid-accessing-data/