我正在使用网格剑桥(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:&#34; pelotas&#34;,Discontinued:undefined,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);
}
我的问题是:存在某种方式将我的数组中的项目创建/更新/删除简单或反应形式传达给我的网格?
答案 0 :(得分: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);
}
}