使用 Angular HTTP 客户端 - 如何发送 POST 所有属性为“默认为 null”的 http 对象

With Angular HTTP client - How to send POST http object with all attribut `null by default`

我的 angular 组件:

const p: Product = this.products.find((d) => d === event.item.data);
p.name = 'foo';

我的 angular 服务是:

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

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

您永远不会从 class 中创建对象,因此永远不会分配 category = null。您使用 class 因为它是一个接口,声明了属性但从未创建它的实例。

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

产品 class 构造函数:

export class Product {
    id: number;
    name: string;
    category: string = null;

    constructor(id: number, name: string) {
      this.id = id;
      this.name = name;
    }
}

现在您的对象将 category 设置为 null

我修补了我的更新,因为我的 GET 没有 return 类别:null

{...new Product(), ...product}

完整代码:

updateProduct(product: Product): Observable<CommonResult> {
    return this.http.put<CommonResult>(this.configService.getApiUri() + '/products/' + product.productId, {...new Product(), ...product});
}