Javascript 角度-未定义到空字段的转换

Javascript 角度-未定义到空字段的转换,javascript,angular,null,undefined,Javascript,Angular,Null,Undefined,我正在用spring后端开发一个angular应用程序。我有一个表单组,如下所示: myForm = new FormGroup({ fieldOne: new FormControl(), fieldTwo: new FormControl(), fieldThree: new FormControl() }); 与以下对象匹配: export class MyClass{ firstField: number; secondField: number;

我正在用
spring
后端开发一个
angular
应用程序。我有一个
表单组
,如下所示:

myForm = new FormGroup({
  fieldOne: new FormControl(),
  fieldTwo: new FormControl(),
  fieldThree: new FormControl()
});
与以下对象匹配:

export class MyClass{
    firstField: number;
    secondField: number;
    thirdField: string;
}
this.firstField = myForm.value.fieldOne;
当我提交表格时,我会这样做:

export class MyClass{
    firstField: number;
    secondField: number;
    thirdField: string;
}
this.firstField = myForm.value.fieldOne;
问题是,如果未设置字段,则它们是未定义的。这会导致无法反序列化对象的后端服务出现问题,因为它不需要
undefined
,而需要
null

这可以解决我的问题:

this.firstField = myForm.value.fieldOne ? myForm.value.fieldOne : null;
但是当我有很多领域的时候,它真的没有那么优雅。 然后我发现了以下作品:

export class MyClass{
    firstField: number = null;
    secondField: number = null;
    thirdField: string = null;
}

那太好了。我的问题是,因为我是新来的
javascript
:对吗?是否有其他最佳实践来进行这种转换?您通常如何解决前端和后端之间的这种序列化问题?谢谢。

我认为你的方法没有任何问题。对于未设置的表单值,默认行为是未定义;根据定义:

undefined属性表示尚未分配变量 价值

当您指定
null
作为默认值时,因为JavaScript null是“nothing”。它应该是不存在的东西。所以,如果后端无法处理未定义的变量,请继续将所有成员变量指定为null


希望这有帮助

如果您想要一个更干净的解决方案,您可以在类中创建一个init函数,将所有值初始化为
null
,如:

export class MyClass{
    firstField: number;
    secondField: number;
    thirdField: string;

    constructor() {
        this.init();
    }

    private init(): void {
        Object.getOwnPropertyNames(this).forEach(
            (property) => {
                this[property] = null;
            }
        );


}

正如@Manu所指出的,您可以分配空值。您还可以定义默认值。如下

export class MyClass{
    firstField: number = 0;
    secondField: number = 0;
    thirdField: string = '';
}

因此,这里不需要处理
未定义的
null
值。这是初始化这样的值的好方法

如果未定义每个字段值,则可以将其设置为null:

var obj = new MyClass();
obj.firstField  = myForm.value.fieldOne;
obj.secondField = myForm.value.fieldTwo;
//...
Object.keys(obj).forEach(field => obj[field] = obj[field] || null);