angular - Reactive Forms type mismatch with data
问题描述
I find that a lot of times there are small differences between the structure of the data I get/post to my web services and the structure of the data needed by my form. What is the best way to handle a mismatch when using reactive forms. Can I have some sort of getter/setter on an individual property in a form group? What would I use for the formGroup name?
Now I am writing two transformation functions - one from my data Model to my formModel that I run onInit before I can patch the formGroup and one from my formModel to my dataModel that I run on save before I can post my data back
For example my webservices get/post this structure has seconds but the UI req is for days.
interface Request
{
name:string,
description:string,
processBy: number //the number of seconds
}
but the UI is just going to to ask for a number of days
interface formModel
{
name:string,
description:string,
processByDays: number
}
<input type="number" formControlName="processByDays" />
I had similar problems with using a custom list control that wanted an array but my data was a scalar so I had a bunch of clunky code just to wrap/unwrap a scalar value.
解决方案
这个问题没有通用的解决方案。但是,您不应该在表单中或表单周围处理这种转换。处理保存数据的服务中的转换。您需要为每个字段执行此操作,因为它是特定于您的业务逻辑的转换。
@Injectable() export class DataService {
save(data: FormModel): Observable<void> {
const {processByDays, ...saveAsIs} = data;
const saveModel: Request = {
...saveAsIs,
processBy: processByDays * 24 * 60 ** 2
};
return this.http.post(myURL, saveModel);
}
}
您可以使用Moment.js来提高可读性。
import moment from 'moment';
const {processByDays, ...saveAsIs} = data;
const saveModel: Request = {
...saveAsIs,
processBy: moment.duration(processByDays, 'days').asSeconds()
};
推荐阅读
- wolfram-mathematica - 将特定规则应用于 Mathematica 中的持有(或未评估)函数
- mongodb - MongoDB按不存在的数组项查找
- faunadb - 为所有活动项目创建索引
- python - 正则表达式命名组的多个订单
- python-3.x - 从每一行中提取 char 的位置并提供列表中的位置聚合
- c - 二进制网格中的旋转点
- javascript - eslint - 异步箭头函数返回值错误
- spring - Spring Java 应用程序更改如何导致“无法验证连接”Hikari 池错误?
- javascript - 获取产品的 AJAX 收集端点
- docker - 无法推送到 Docker Hub - 标签不存在