node.js - 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
}
关于如何实现这一目标的任何想法或建议?
提前致谢!
解决方案
您可以保留“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);
}
}
注意:在示例中,我使用“数组语法”来使用变量来访问并在对象上创建属性。
推荐阅读
- c# - 在字符串中定义的我的类名的实例列表
- react-native - 在 webview react_native 中处理单击按钮或取消划线文本
- c++ - QML 参考错误 -
在 c++/QML 集成期间未定义 - reactjs - React 懒惰 vs Intersection 观察者 API
- azure - Azure AD:如何为应用设置自定义权限?
- react-native - 解析错误:意外的令牌,预期的,
- react-native - React-native-fetch-blob 创建 .apk 文件时出错
- android - 如何以编程方式“清除应用数据”然后“重新启动”Android 应用?
- python - 为什么 _siftup 和 _siftdown 在 Python 中正好相反?
- powershell - 更新 Active Directory 用户配置文件 (userCertificate) 上的证书