【问题标题】:Handling nested data in reactive forms以反应形式处理嵌套数据
【发布时间】:2018-02-11 21:33:54
【问题描述】:

我必须做一个POST,所以我们经常做这样的事情:

const userData = this.userForm.value;

假设在你的模板中:

<input type="text" id="userName" formControlName="userName">
<input type="email" id="userEmail" formControlName="userEmail">
<select id="userTypeId" formControlName="userTypeId">
  <option *ngFor="let userType of userTypes" [value]="userType.id">{{userType.name}}</option>
</select>

然后在您的userData 中,您将拥有:

{
  userName: 'foo',
  userEmail: 'foo@bar.com',
  userTypeId: '1'
}

这很好,但现在您的 API 正在等待:

{
  userName: string,
  userEmail: string,
  userType: UserType
}

在哪里UserType

{
  id: string,
  name: string,
}

所以你最终会这样做:

const userForAPI = {
  userName: userData.userName,
  userEmail: userData.userEmail,
  userType: { id: userData.userTypeId }
}

然后你去

this.userService.createUser(userForAPI)

现在,我想知道是否有不做的替代解决方案:

userType: { id: userData.userTypeId }

我的意思是,如果您可以根据api的模型对模板进行建模,以便您可以将this.userForm.value发送给api。

【问题讨论】:

  • 我会说最好的替代方法是修复 API:如果它实际需要的只是用户 ID,为什么它会要求具有 ID 和名称的用户对象?也就是说,具有与 API 命令结构不匹配的表单结构并在发布请求之前调整结构并没有错。表单结构应该是网页中表单所需要的,而不是API所需要的。
  • 这是我的第一印象,但它是被请求的,但它是一个用 graphql 制作的 API,所以我真的是所谓的突变,而不仅仅是一个简单的调用。现在,重点不同了。

标签: angular typescript graphql angular-reactive-forms


【解决方案1】:

如果您使用ngValue 而不是value,则选择/选项控件的值可以是自定义对象,而不仅仅是字符串。这意味着您可以将模型更改为使用userType 而不是userTypeId

<select id="userType" formControlName="userType">
  <option *ngFor="let userType of userTypes" [ngValue]="userType">{{userType.name}}</option>
</select>

模型现在将包含例如以下内容。

{
  userName: 'foo',
  userEmail: 'foo@bar.com',
  userType: {id: '1', name: 'foo1'},
}

这是demo

【讨论】:

  • @FacundoGFlores 试用并添加了一个演示;这个对我有用。可能是其他原因导致您的情况出现问题。
  • 我错过了 [ngValue] 它正在工作,抱歉。只是一件事,你知道为什么patchValue 不起作用吗?我的意思是我将对象正确发送到表单,但没有“选择”用户类型。
  • 更新了demo,可以看到可以工作了(显示baz而不是初始化的foo)。
猜你喜欢
  • 1970-01-01
  • 2018-11-04
  • 2019-06-04
  • 1970-01-01
  • 2022-11-30
  • 2017-07-21
  • 2018-04-16
  • 2017-07-03
  • 2017-08-04
相关资源
最近更新 更多