Had*_*adi 2 angular angular-httpclient
当我想将信息作为 post 方法发送到我的 Rest API 时,Angular 会发送空字段,随后我的数据库会保存空值。
但我想阻止它,并且我不想将空字段从我的 Angular 发送到我的后端。
例如,在下面的示例中,Angular 在entityTypeName 字段中发送“”,不幸的是,Postgres DB 将保存空而不是空。
{
createdAt: "2019-01-11T13:59:52.311678"
entityTypeName: ""
id: "1bd46fce-fc6f-410f-acaf-74d5964cf92b"
updatedAt: "2019-01-11T13:59:52.311678"
updatedBy: "admin@admin.com"
version: 0
}
Run Code Online (Sandbox Code Playgroud)
我正在寻找一种通用的解决方案,以防止在所有情况下在 Angular 端发送空值。
小智 5
这是一个执行此操作的函数。只需将您的对象提供给该函数,它就会删除空键。
function removeEmptyStringsFrom(obj) {
const clone = { ...obj };
Object.entries(clone).forEach(([key, val]) => val === '' && delete clone[key]);
return clone;
}
const test = {
notEmpty: 'toto',
empty: '',
};
console.log(removeEmptyStringsFrom(test));Run Code Online (Sandbox Code Playgroud)
编辑:接受挑战!
const removeEmptyStringsFrom = (obj) => Object
.entries({ ...obj })
.filter(([key, val]) => val !== '')
.reduce((prev, curr) => ({ ...prev, [curr[0]]: curr[1] }), {});
const test = {
notEmpty: 'toto',
empty: '',
};
console.log(removeEmptyStringsFrom(test));Run Code Online (Sandbox Code Playgroud)