【问题标题】:Angular 2 : Trouble with asynchronous dataAngular 2:异步数据的问题
【发布时间】:2017-06-05 13:39:53
【问题描述】:

我做了一个提供数据的服务。当我直接返回数据时,它可以工作:

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 和数据源)。我不确定它是否相关。

我的代码是这样的:

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()">

提前致谢。

【问题讨论】:

    标签: angular observable ag-grid


    【解决方案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
    

    【讨论】:

    • foofood?一定有人饿了;-)
    • 谢谢。当我尝试第一个解决方案时,出现错误:error_handler.js:50 EXCEPTION: Uncaught (in promise): Error: Error in ./myComponent class MyComponent - inline template:0:0 cause: Cannot read property 'forEach'未定义错误:./MyComponent 类 MyComponent 中的错误 - 内联模板:0:0 原因:无法读取未定义的属性“forEach”
    • 能否提供更多的实现细节?您提供的代码 sn-p 似乎并未显示您实际使用此方法的方式。此外,也许您也可以提供任何 html/模板代码。
    • 所有的 FakeData 方法都返回 this._getDataFromJson(this._generateUrl(someParams)。我已经添加了我的模板。
    • 好吧,如果您使用第一个解决方案,那么您的 fakeData 方法可能也会返回承诺。对不起,很难说发生了什么事。根据您编写此代码的方式,您可能还需要将 fakeData 方法也作为 Promise 处理。另外,不确定你是否看过这个,但也许这个 ext 可以帮助你检查绑定到你的组件元素的内容:github.com/rangle/augury
    猜你喜欢
    • 2019-04-11
    • 1970-01-01
    • 1970-01-01
    • 2018-04-24
    • 2019-11-25
    • 1970-01-01
    • 2018-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多