2016-10-25 32 views
0

我使用劍道的網格(角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

概述

我聲明一個數組:

私有視圖:數組= [{產品編號:1,產品名稱:「pelotas」,停產:undefined,UnitsInStock:80}];

,並重寫獲取方法是這樣的:

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); 
} 

我的問題是:存在的某種方式傳達創建/更新/刪除我的一個簡單的或反應形式到我的網格陣列的項目?

回答

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); 
    } 
}