angular - 如何防止在 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 端发送空值。
解决方案
这是一个功能。只需将您的对象提供给该函数,它就会删除空键。
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));
推荐阅读
- laravel - Laravel - 单一登录的多个项目
- mongodb - 检查字段包含包含特殊字符 mongodb 的字符串
- image-processing - 无法在 google colab 上使用 PIL 显示图像
- html - 在烧瓶中选择并归档输入表单数据
- angular - Angular:从组件更新 ngModel 数据时,UI 更改不会更改模型值
- c# - 在 ASP.NET CORE 中动态更改 Route 属性值
- php - 如何单击提交按钮立即更新 MySQL 并重新加载 php 中的表格内容?
- c# - WPF Wrap ListView 或 Grid DataTable
- reactjs - 从同级 React 组件中的表单提交刷新一个子 React 组件
- javascript - 如何让标题在网页上只淡出一次(添加 java 脚本类)