0

我正在使用剑道网格(Angular 2)在网格中添加/编辑/删除一行:

http://www.telerik.com/kendo-angular-ui/components/grid/editing/

在原始代码中,数据是从这样的休息服务中获取的:

    private fetch(action: string = "", data?: Product): Observable<Product[]>  {
        return this.jsonp
        .get(`http://demos.telerik.com/kendo-ui/service/Products/${action}?  callback=JSONP_CALLBACK${this.serializeModels(data)}`)
        .map(response => response.json());
     }

但是,我想使用一个数组来添加/编辑/删除内存中的行。接下来,我想单击按钮提交并将数据(包括我的所有更改)发送到服务器。

我的解决方案是这样的:

https://gist.github.com/joedayz/9e318a47d06a7a8c2170017eb133a87e

概述

我声明一个数组:

私人视图:Array = [{ProductID:1,ProductName:“pelotas”,停产:未定义,UnitsInStock:80}];

并像这样覆盖 fetch 方法:

  private fetch(action: string = "", data?: Product): Observable<Product[]>    {
/*return this.jsonp
  .get(`http://demos.telerik.com/kendo-ui/service/Products/${action}?callback=JSONP_CALLBACK${this.serializeModels(data)}`)
  .map(response => response.json());*/

  debugger;

  if(action=="create"){
    var product : Product = new Product(-1, data.ProductName, data.Discontinued, data.UnitsInStock);
    this.view.push(product);
  }else if(action=="update"){
    var indice = this.view.indexOf(data);

    if(indice>=0)
    this.view[indice]  = (JSON.parse(JSON.stringify(data)));
  }else if(action=="destroy"){
    var indice = this.view.indexOf(data);

    if(indice>=0)
    this.view.splice(indice, 1);

  }


  return Observable.of(this.view);
 }

我的问题是:是否存在某种方式将我的简单或反应形式数组中项目的创建/更新/删除传达给我的网格?

4

1 回答 1

0

当你使用内存数组时,你不需要使用 Observables。Grid 组件已经绑定到数组,因此只需要操作数据即可。例如:

export class AppComponent {
    public dataItem: Product;

    @ViewChild(GridEditFormComponent) protected editFormComponent: GridEditFormComponent;

    private view: Array<Product> = [{ ProductID: 1, ProductName: "pelotas", Discontinued: undefined, UnitsInStock: 80 }];

    public onEdit(dataItem: any): void {
        this.dataItem = Object.assign({}, dataItem);
    }

    public onCancel(): void {
        this.dataItem = undefined;
    }

    public addProduct(): void {
        this.editFormComponent.addProduct();
    }

    public onSave(product: Product): void {
        if (product.ProductID === undefined) {
            this.createProduct(product);
        } else {
            this.saveProducts(product);
        }
    }

    public onDelete(e: Product): void {
        this.deleteProduct(e);
    }

    public saveProducts(data: Product): void {
        var index = this.view.findIndex(x => x.ProductID === data.ProductID);

        if (index !== -1) {
            this.view = [
                ...this.view.slice(0, index),
                data,
                ...this.view.slice(index + 1)
            ];
        }
    }

    public createProduct(data: Product): void {
        this.view = [...this.view, data];
    }

    public deleteProduct(data: Product): void {
        this.view = this.view.filter(x => x.ProductID !== data.ProductID);
    }
}
于 2016-10-26T11:33:24.953 回答