的反应形式

的反应形式

问题描述:

我必须做一个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: '[email protected]', 
    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。

+0

我想说最好的选择是修复API:为什么它要求一个带有ID和名称的用户对象,如果它实际上需要的是一个用户ID?也就是说,有一个与API命令结构不匹配的表单结构并且在发布请求之前调整结构是没有问题的。表单结构应该是网页中表单所需的表单结构,而不是API所需的表单结构。 –

+0

这是我的第一印象,但它是请求,但在graphql中制作的API,所以我真的只是一个简单的调用所谓的突变。现在,这一点是不同的。 – FacundoGFlores

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

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

例如,该模型将包含以下内容。

{ 
    userName: 'foo', 
    userEmail: '[email protected]', 
    userType: {id: '1', name: 'foo1'}, 
} 

这里有一个demo

+0

@FacundoGFlores试了一下,并添加了一个演示;这个对我有用。这可能是其他情况导致您的案件中的问题。 –

+0

我错过了'[ngValue]'它正在工作,对不起。只有一件事,你知道为什么'patchValue'不工作吗?我的意思是我正确地将对象发送到窗体,但没有“选择”用户类型。 – FacundoGFlores

+0

更新了演示,你可以看到它的工作原理(显示'baz'而不是初始化'foo')。 –