首页 > 解决方案 > 如何防止在 Angular HttpClient.post 方法中发送空字段?

问题描述

当我想将信息作为 post Method 发送到我的 Rest API 时,Angular 会发送空字段,随后,我的数据库会保存空值。

但我想阻止它,我不想将空字段从我的 Angular 发送到我的后端。

例如,在下面的示例中,Angular 在 entityTypeName 字段中发送了一个“”,不幸的是,Postgres DB 将保存为空而不是 null。

{ 
   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 
}

我正在寻找一种通用解决方案,以防止在所有情况下在 Angular 端发送空值。

标签: angularangular-httpclient

解决方案


这是一个功能。只需将您的对象提供给该函数,它就会删除空键。

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

编辑:接受挑战!

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


推荐阅读