Angular2 ag-grid数据源无法正常工作

时间:2016-07-13 10:52:57

标签: typescript angular ag-grid

我正在努力让我的ag-grid工作,但是我收到了错误。

以下是代码:

import { Component, OnInit } from '@angular/core';
import {AgGridNg2} from 'ag-grid-ng2/main';
import {GridOptions} from 'ag-grid/main';


import {ClientsService} from './clients.service';

@Component({
    moduleId: module.id,
    selector: 'clients',
    directives: [AgGridNg2],
    templateUrl: 'clients.component.html',
    providers: [ClientsService]
})
export class ClientsComponent implements OnInit {

    private gridOptions: GridOptions;
    private showGrid: boolean;
    private rowData: any[];
    private columnDefs: any[];
    private rowCount: string;

    constructor(private _clientsService : ClientsService) {

        this.gridOptions = <GridOptions>{};
        this.createColumnDefs();
        this.showGrid = true;

        this.gridOptions = {
            columnDefs: this.columnDefs,
        }   

         this.gridOptions = <GridOptions>{
            onGridReady: () => {
                this.gridOptions.api.sizeColumnsToFit();
                this.gridOptions.api.setDatasource(this.dataSource);
            }
        };


     }

    ngOnInit() { }

    dataSource = {
        pageSize: 10,
        overflowSize: 100,

       getRows: (params: any) => {
            this.returnRows().subscribe(data => {

                var test =
                    [{"ClientName":"Ronald Bowman","Country":"China","CreatedOn":"Lutou","email":"rbowman0@spotify.com"},
                    {"ClientName":"Pamela Hill","Country":"Russia","CreatedOn":"Krylovskaya","email":"phill1@symantec.com"},
                    {"ClientName":"Robin Andrews","Country":"Ukraine","CreatedOn":"Korop","email":"randrews2@photobucket.com"},
                    {"ClientName":"Peter Kim","Country":"Mexico","CreatedOn":"San Jose","email":"pkim3@theatlantic.com"},
                    {"ClientName":"Carol Foster","Country":"Mexico","CreatedOn":"El Aguacate","email":"cfoster8@intel.com"},
                 ];

                 var rowsThisPage = data.slice(params.startRow, params.endRow);

                 var lastRow = -1;

                 params.successCallback(rowsThisPage, lastRow);

            });
        }
    }


    private returnRows(){
        return this._clientsService.getClientsForDataTable();
    }   


     private createColumnDefs() {
        this.columnDefs  = [
            {headerName: 'Client Name', field: "ClientName", width: 200 },
            {headerName: 'Country', field: "Country" ,width:180},
            {headerName: 'Created On', field: "CreatedOn" ,width:160}
        ];
    }

}

这是我的服务,它从后端获取数据为JSON:

import { Injectable } from '@angular/core';

import {Http, Response, Headers} from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { GlobalVariablesService } from '../../shared/global/global-variables.service';

@Injectable()
export class ClientsService {

    constructor(public _http:Http, private _globalVariables: GlobalVariablesService) { 

    }

    getClientsForDataTable() {
            return this._http.get(this._globalVariables.BACKEDN_API_GET_ALL_CLIENTS_FOR_DATA_TABLE) 
           .map((res:Response) => res.json())
           .catch(this.handleError);
    }

    private handleError (error: Response) {
        console.error(error);
        return Observable.throw(error.json().error || 'Server error');
  }
}

正如您在上面的组件中所看到的,当尝试使用硬编码的JSON数据时,它可以正常工作,但是当我用实际的HTTP响应替换它时,我会收到错误,如下所示:

getRows: (params: any) => {
            this.returnRows().subscribe(data => {

                var test =
                    [{"ClientName":"Ronald Bowman","Country":"China","CreatedOn":"Lutou","email":"rbowman0@spotify.com"},
                    {"ClientName":"Pamela Hill","Country":"Russia","CreatedOn":"Krylovskaya","email":"phill1@symantec.com"},
                    {"ClientName":"Robin Andrews","Country":"Ukraine","CreatedOn":"Korop","email":"randrews2@photobucket.com"},
                    {"ClientName":"Peter Kim","Country":"Mexico","CreatedOn":"San Jose","email":"pkim3@theatlantic.com"},
                    {"ClientName":"Carol Foster","Country":"Mexico","CreatedOn":"El Aguacate","email":"cfoster8@intel.com"},
                 ];

                 var rowsThisPage = data.slice(params.startRow, params.endRow);

                 var lastRow = -1;

                 params.successCallback(rowsThisPage, lastRow);

            });
        }

这是错误:

  

EXCEPTION:TypeError:rowData.forEach不是函数       TypeError:rowData.forEach不是函数           at recursiveFunction(inMemoryRowModel.js:355)           at InMemoryRowModel.createRowNodesFromData(inMemoryRowModel.js:330)           在InMemoryRowModel.setRowData(inMemoryRowModel.js:296)           在PaginationController.pageLoaded(paginationController.js:138)           at Object.successCallback(paginationController.js:210)           在SafeSubscriber.eval [as _next](clients.component.ts:64)           在SafeSubscriber .__ tryOrUnsub(Rx.js?1467025050775:10855)           在SafeSubscriber.next(Rx.js?1467025050775:10810)           在Subscriber._next(Rx.js?1467025050775:10766)           在Subscriber.next(Rx.js?1467025050775:10743)

我已经测试了来自'data'的JSON结果,它应该没问题,因为我刚刚复制并替换它而不是测试数据。

有人可以帮我解决这个错误吗?

4 个答案:

答案 0 :(得分:2)

数据应该是数据对象的数组。我的猜测是你的数据是一个字符串(json)。你需要将json转换为数据数组。

答案 1 :(得分:1)

好的,我把它修好为:

dataSource = {
    pageSize: 10,
    overflowSize: 100,

    getRows: (params: any) => {
        this.returnRows(params.startRow, params.endRow).subscribe(data => {
            var convertedDataToArray = JSON.parse(data);

             var lastRow = -1;

             params.successCallback(convertedDataToArray, lastRow);

        });
    }
}

答案 2 :(得分:0)

我使用React收到同样的错误。这是在查找错误时弹出的答案,因此我将在此回复,因为ag-gridReact的{​​{1}}类似。

在我的情况下,这是因为我试图将对象分配给网格而不是数组。由于Angular的不变性要求,我这样做了:

Redux

应该是这样的:

Object.assign({}, items)

答案 3 :(得分:0)

我刚遇到这个问题。我正在使用“ ag-grid-angular”:“ ^ 18.1.0”。 添加了onGridReady事件,以填充在ag-grid-angular标签中添加属性(gridReady)="onGridReady($event)"的网格数据。

当我尝试填充数据时,它显示了如上所述的错误。

尝试了几件事之后,我添加了agGrid:AgGridNg2;变量并导入引用,它开始正常工作。代码纺锤如附件所示。

export class AppointmentComponent implements OnInit { @ViewChild('agGrid') agGrid: AgGridNg2;