【发布时间】: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