首页 > 解决方案 > Angular 中的动态表仅将更改的数据发送到 API

问题描述

我正在尝试在 Angular 中实现动态表的功能,其中数据首先来自后端(Express),然后填充数据。我还可以向表中添加新行并通过它发送数据。

我可以通过使用 formdata 将表的所有数据发送到 API 来成功地做到这一点。现在我只想将我更改的数据发送到 API,而不是整个数据。

这是我的桌子:

在此处输入图像描述

在 ngOnInit() 上,我正在调用 API 并保存数据,例如this.collections = res.data

在添加行上,新行被添加代码:

addImage() {
    const obj: Collection = {
      uid: '',
      image: '',
      description: '',
      price: ''
    }
    this.collections.push(obj)
  }

在更改输入字段中的文本时,我正在使用(input)属性并将数据传递给onInputChange()

onInputChange(text: string, i: string, property: string) {
    this.collections[i][property] = text
 }

现在我this.collections将拥有我通过保存按钮上的 POST API 调用发送的所有数据,即这里的所有 3 行。

如果我不进行任何更改,仍然this.collections会发送该数据。我想要的只是发送更改的数据(就像我只更改了 1 行,所以只发送数据)

我尝试通过创建一个新的空collecctionToAdd对象并像这样在 onInputChange() 上向其中添加数据来实现它,但是由于它是在(input)事件中,因此它会针对每个文本字段不断变化。

if(this.collections[i][property] !== text) {
      this.collectionToAdd[i][property] = text
}

关于如何实现这一目标的任何想法或建议?

提前致谢!

标签: node.jsangulartypescriptapiexpress

解决方案


您可以保留“collecctionToAdd”逻辑。

我猜你有一个“this.collections”的ngFor。因此,您需要执行以下操作*ngFor="let item of collections; let i = index"才能获取原始集合中元素的索引,然后:

将 collecctionToAdd 初始化为空对象:

private collecctionToAdd = {};

做一个这样的函数:

rowChange(text: string; field: string, index: number){
  if(!this.collecctionToAdd[index]){
    // use spread operator in order to keep the original object untouched or not. Remove it if u want
    this.collecctionToAdd[index] = {...this.collecction[index]};
  }
  this.collecctionToAdd[index][field] = text;
}

并在您的提交功能中:

submit(){
   const rowsToSubmit = []
   for (const key in this.collecctionToAdd) {
         const element: any = this.collecctionToAdd[key];
         rowsToSubmit.push(element);
     }

}

注意:在示例中,我使用“数组语法”来使用变量来访问并在对象上创建属性。


推荐阅读