如何在angular2中使用带有Observable的ag-grid? [英] How can I use ag-grid with Observable in angular2?

查看:66
本文介绍了如何在angular2中使用带有Observable的ag-grid?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在Internet上进行了大量研究,但仍然无法将它们结合在一起.我有一个angular2应用程序,带有来自HTTP的Observable数据源,并且想使用ag-grid.问题是我只有一个加载屏幕而不是数据.我已经使用Fiddler进行了调查,数据已成功且正确地以JSON加载.这是我的代码:

I have done lots of research on Internet but still cannot glue these together. I have an angular2 application, with Observable data source from HTTP, and would like to use ag-grid. The problem is I only got a loading screen instead of the data. I have investigated with Fiddler, the data is loaded successfully and correctly in JSON. Here is my code:

order.service.ts

order.service.ts

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

import { Observable }    from 'rxjs/Observable';

import { Order } from './order';

@Injectable()
export class OrderService {

  private ordersUrl = '(Some JSON data source via Internet)';  // URL to web api

  constructor(private http: Http) { } 

  getOrders(): Observable<Order[]> {
    return this.http.get(this.ordersUrl)
        .map(this.extractData)
        .catch(this.handleError);
  }

  save(order: Order): Observable<Order>  {
    if (order.id) {
      //return this.put(order);
    }
    return this.post(order);
  }

  delete(order: Order) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');

    let url = `${this.ordersUrl}/${order.id}`;

    return this.http
       .delete(url, headers)
       .map(this.extractData)
       .catch(this.handleError);
  }

  // Add new Order
  private post(order: Order): Observable<Order> {
    let headers = new Headers({
      'Content-Type': 'application/json'});

    return this.http
               .post(this.ordersUrl, JSON.stringify(order), {headers: headers})
               .map(this.extractData)
               .catch(this.handleError);
  }

    private extractData(res: Response) {
        let body = res.json();
        return body.data || { };
    }

    private handleError (error: any) {
        // In a real world app, we might use a remote logging infrastructure
        // We'd also dig deeper into the error to get a better message
        let errMsg = (error.message) ? error.message :
            error.status ? `${error.status} - ${error.statusText}` : 'Server error';
        console.error(errMsg); // log to console instead
        return Observable.throw(errMsg);
    }
}

order.component.ts

order.component.ts

import { Component, OnInit } from '@angular/core';
import { Router }            from '@angular/router';

import { AgGridNg2 } from 'ag-grid-ng2/main';

import { Order }                from './order';
import { OrderService }         from './order.service';


@Component({
  selector: 'my-orders',
  templateUrl: 'app/order/order.html',
  directives: [ AgGridNg2 ]
})

export class OrderComponent implements OnInit {
    errorMessage: string;
    orders: Order[];
    selectedOrder: Order;
    addingOrder = false;
    error: any;
    mode = 'Observable';
    gridOptions: any = [];

    ngOnInit() {
        this.getOrders();
    }

    columnDefs = [(Some definition)];

    getOrders() {
        this.orderService
            .getOrders()
            .subscribe(
               orders => this.orders = orders,
               error =>  this.errorMessage = <any>error);
    }

    constructor(
        private router: Router,
        private orderService: OrderService) {
            orderService
                .getOrders()
                .subscribe(
                   orders => this.orders = orders,
                   error =>  this.errorMessage = <any>error);

            this.gridOptions = {
                rowData: this.orders,
                columnDefs: this.columnDefs,
                enableColResize: true,
                enableSorting: true,
                enableFilter: true
            }
        }

    onSelect(order: Order) {
        this.selectedOrder = order;
        this.addingOrder = false;
    }
}

以上代码是从Google教程复制而来的,仅作了一些修改,仅供参考.

The above code was copied from Google tutorial with some modifications and for demonstration only.

这是HTML文件,除了一个标签,它仅包含一个ag-grid标签

Here is the HTML file, it contains nothing but one tag for ag-grid

<ag-grid-ng2 #agGrid style="width: 100%; height: 350px;" class="ag-fresh" [gridOptions]="gridOptions">
</ag-grid-ng2>

预先感谢您拯救我的生命.

Thank you in advance for saving my life.

推荐答案

好的,所以您使用Observable的流程对我来说很好,但是您没有将订单绑定到表格:

Okay, so your flow with the Observable looks fine to me, but you don't bind the orders to the grid:

<ag-grid-ng2 
    #agGrid 
    style="width: 100%; height: 350px;" 
    class="ag-fresh" 

   [gridOptions]="gridOptions"
   [rowData]="orders">
</ag-grid-ng2>

或者,您可以将gridOptions的设置移到订阅回调中:

Alternatively you could move the setting of the gridOptions into the subscribe callback:

    private orderService: OrderService) {
        orderService
            .getOrders()
            .subscribe(
                orders => { 
                    this.orders = orders;

                    this.gridOptions = {
                        rowData: this.orders,
                        columnDefs: this.columnDefs,
                        enableColResize: true,
                        enableSorting: true,
                        enableFilter: true
                    };
                },
                error =>  this.errorMessage = <any>error
            );
    }


此Github存储库有一些有关如何使用ag-grid-ng2的很好的示例.


This Github Repository has some good examples on how to use ag-grid-ng2.

这篇关于如何在angular2中使用带有Observable的ag-grid?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆