【问题标题】:Send just the model PK (or any other field) for nested model in Angular仅发送 Angular 中嵌套模型的模型 PK(或任何其他字段)
【发布时间】:2021-08-27 20:04:17
【问题描述】:

具有以下示例模型:

interface User {
  id: string
  organization: Organization
}

interface Organization {
  id: string
}

当我发送请求时,例如:

const user = new User("abc", new Organization("xyz"))
httpClient.post<User>(url, user)

可以理解,它看起来像这样:

{
  "id": "abc",
  "organization": {
    "id": "xyz"
  }
}

我怎样才能发送如下所示的请求?

{
  "id": "abc",
  "organization": "xyz"
}

我希望有某种机制来转换HttpClient 中的请求,但我找不到任何东西。

另一种方法是将User 转换为普通的 JS 对象并对其进行操作,但我不知道该怎么做:

const user = new User("abc", new Organization("xyz"))
const data = Object.assign({}, user);

data.organization = data.organization.id; // error, can’t assign string to Organization

所以data 仍然是User,而不是普通的 JS 对象。

实现它的最佳方法是什么?

【问题讨论】:

标签: angular typescript angular-httpclient


【解决方案1】:

所以 data 仍然是一个用户,而不是一个普通的 JS 对象。

您正在创建一个 User 实例来发送数据,并且对象数据的类型始终为 User

如果你想发送普通对象,解构对象并创建一个对象字面量:

const org = new Organization("xyz"), 
      user = new User("abc", {organization: org.organization.id}),             
      {id, organization} = user,
      payload = {id, organization};

// why do you need to create org or user if you can directly assign and create an object like this

// const payload = {id: "abc" , organization: "xyz" };
httpClient.post<User>(url, payload)

【讨论】:

  • 您的第一个解决方案将不起作用,因为organization 必须是Organization 类型,它具有id 属性,并且您正在传递一个具有organization 属性的普通对象。我知道数据类型是User。我说的是在使用Object.assign({}, user) 创建一个新的(看似简单的)对象后,数据类型仍然是User。至于如果我可以“直接分配和创建对象”,我为什么要使用模型:模型提供了数据安全性,并且可选地提供了操作数据的方法。普通对象两者都做不到。
  • Object.assign({}, user) 克隆/复制对象,因此它也从实例复制类型,检查thisYour first solution won’t work 是的,如果您在用户类中有类型检查是可能的。
  • 你应该检查this
【解决方案2】:

我找到了一种解决方案,但我不是 100% 满意。我暂时不接受,以防有人能提供更好的。

编辑:标记为已接受的答案。

const user = new User("abc", new Organization("xyz"));

// clone the `user` object as I don’t want to modify the original
// (this step is optional)
const data = Object.assign({}, user);

// overwrite the `organization` property on the object
// with the value of `organization.id`
Object.assign(data, { organization: data.organization.id });

httpClient.post<User>(url, data)

为了保持整洁,我将其作为方法添加到 User 类中:

class User
{
    constructor(
        id: string,
        organization: Organization
    ) { }

    asRequestData()
    {
        const data = Object.assign({}, this);
        Object.assign(data, { organization: data.organization?.name });

        return data;
    }
}

httpClient.post<User>(url, user.asRequestData())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-29
    • 1970-01-01
    相关资源
    最近更新 更多