首页 > 解决方案 > 使用 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"
}

我无法访问我的后端代码(我无法更改后端代码)。如何修补我的前端代码以解决我的问题?

标签: angularangular-httpclient

解决方案


你永远不会在你的类之外创建一个对象,因此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


推荐阅读