我提供了一项提供数据的服务。当我直接返回数据时,它可以工作:
When I return directly the data, it works. Like that :
return [
{
"prop1": "value1",
"prop2": "value2"
},
{
"prop1": "value3",
"prop2": "value6"
}
];
但是当我尝试从JSON文件中获取它们时,它不会:
// Get Data from JSON
private _getDataFromJson(url: string) {
return this.http.get(url)
.toPromise()
.then(res => res.json())
.then(data => { return data; })
}
// I also tested that
/*return this.http.get(this._generateUrl(type, 'column-def'))
.map(res => res.json());*/
我正在将这些json文件数据用于ag网格(默认colDef,colDef,floatingTopRows和datasource)。我不确定它是否相关。
我的代码看起来像这样:
ngOnInit() {
this.defaultColDef = this.FakeData.getColumnDefDefault();
this.colDef = this.FakeData.getColumnDef(this.dataType);
this.floatingTopRowData = this.FakeData.getFloatingTopRows(this.dataType);
this.allOfTheData = this.FakeData.getData(this.dataType);
this.gridOptions = <GridOptions> {
onGridReady: () => {
this._populateData();
}
};
}
其他相关方法:
_populateData(): void {
this.allOfTheData.then(rowData => {
this._setRowData(rowData);
this.pageSizes = this._generatePageSizes(rowData.length);
});
}
_setRowData(rowData): void {
this.allOfTheData = rowData;
this._createNewDatasource();
}
_createNewDatasource(): void {
if(!this.allOfTheData) return;
let dataSource = {
getRows: (params: any) => {
this.sortedAndFilteredData = this._sortAndFilter(params.sortModel, params.filterModel);
let rowsThisPage = this.sortedAndFilteredData.slice(params.startRow, params.endRow);
params.successCallback(rowsThisPage, this.sortedAndFilteredData.length);
}
};
this.gridOptions.api.setDatasource(dataSource);
}
修改
我的模板:
<ag-grid-ng2 #agGrid [id]="id" style="width: 100%;" [style.height.px]="gridHeight" class="ag-bootstrap" (modelUpdated)="setHeight()"
[gridOptions]="gridOptions"
[defaultColDef]="defaultColDef"
[columnDefs]="colDef"
[floatingTopRowData]="floatingTopRowData"
enableColResize
enableServerSideSorting
enableServerSideFilter
suppressDragLeaveHidesColumns
suppressMultiSort
rowModelType="pagination"
[headerHeight]="headerHeight"
[rowHeight]="rowHeight"
rowSelection="multiple"
(dragStopped)="_onColumnMoved()"
(selectionChanged)="_onSelectionChanged()">
提前致谢。
答案 0 :(得分:1)
private _getDataFromJson(url: string) {
return this.http.get(url)
.toPromise()
.then(res => res.json())
.then(data => { return data; })
}
此方法返回一个promise,因此,调用方法需要使用promise来获取数据。
所以调用_getDataFromJson(url)
看起来像这样:
this._getDataFromJson(someUrl).then(data => this.foo = data);
或者因为你正在使用Typescript,你可以使用async / await:
this.foo = await this._getDataFromJson(someUrl); // don't forget the async keyword on the enclosing method