angular - 使用 Angular HTTP 客户端 - 如何发送所有属性为“默认为空”的 POST http 对象
问题描述
我的角度分量:
const p: Product = this.products.find((d) => d === event.item.data);
p.name = 'foo';
我的角度服务是:
updateProduct(product: Product): Observable<CommonResult> {
return this.http.put<CommonResult>(this.configService.getApiUri() + '/products/' + product.productId, product);
}
我的产品型号:
export class Product {
id: number;
name: string;
category: string = null;
}
我想:
{
id: 1
name: "foo",
category: null
}
但是我有:
{
id: 1
name: "foo"
}
我无法访问我的后端代码(我无法更改后端代码)。如何修补我的前端代码以解决我的问题?
解决方案
你永远不会在你的类之外创建一个对象,因此category = null
永远不会被分配。您使用该类,因为它是一个接口,声明了属性但从未创建它的实例。
export class Product {
id: number;
name: string;
category: string = null;
}
为了将类别设置为 null,您必须使用new Product()
,并可能为其他属性设置构造函数:
const productResult = this.products.find((d) => d === event.item.data);
const p: Product = new Product(productResult.id, 'foo');
带有构造函数的产品类:
export class Product {
id: number;
name: string;
category: string = null;
constructor(id: number, name: string) {
this.id = id;
this.name = name;
}
}
现在您的对象将category
设置为 null
推荐阅读
- webpack - 来自 CDN 的 Webpack 外部,用于 UMD 应用程序
- docker - 从一个 docker-compose 托管 docker swarm,但使用节点 var
- intellij-idea - 在 Intellij Idea 的编辑器中启用类型信息
- python - 使用 Python 使用 Selenium 进行 Web 抓取 - 不检索所有元素
- sql - 获取具有最大总缺陷数量的缺陷类型
- javascript - 从图库中选择新图像并在不重新加载页面的情况下显示它
- sql-server - Spring R2DBC - 使用 Windows 身份验证连接到 SQL Server 数据库
- model - 如何在 SABR 的到期日之间插入隐含掉期波动率?
- git - PR完成后到主分支的不同提交号
- python - 查找最旧的并以特定用户输入结束