typescript 如何将嵌入/嵌套FormGroup转换为FormData

yftpprvb  于 2023-06-07  发布在  TypeScript
关注(0)|答案(5)|浏览(271)

这是我的表单组:

this.shopGroup = this.fb.group({
  _user: [''],
  name: ['', Validators.compose([Validators.required, Validators.maxLength(60)])],
  url_name: [''],
  desc: ['', Validators.compose([Validators.required, Validators.maxLength(600)])],
  photos: [''],
  currency: ['Real'],
  language: ['Português do Brasil'],
  address: this.fb.group({
    zipcode: ['', Validators.compose([Validators.required, Validators.pattern('[0-9]{5}[\-]?[0-9]{3}')])],
    street: ['', Validators.compose([Validators.required, Validators.maxLength(70)])],
    number: [null, Validators.compose([Validators.required, Validators.max(99999)])],
    complement: ['', Validators.maxLength(30)],
    district: ['', Validators.compose([Validators.required, Validators.maxLength(60)])],
    state: ['', Validators.required],
    city: ['', Validators.compose([Validators.required, Validators.maxLength(70)])]
  }),
  status: [true],
  created_at: [new Date()],
  updated_at: [new Date()]
});

我需要将其转换为FormData,因为我要将图像上传到服务器(Multer包),但是,我不确定如何处理address组,就像shopGroup表单数据中的新对象一样。下面是我正在做的从FormGroup转换为FormData(地址不起作用):

const shopData: any = new FormData();
shopData.append('name', shopGroup.get('name').value);
shopData.append('zipcode', shopGroup.get('address').get('zipcode').value);
...

如何进行转换(Json到FormData)并处理像address这样的嵌入/嵌套对象?

bqjvbblv

bqjvbblv1#

好了,我找到了一个将JSON对象转换为FormData的函数:

convertJsontoFormData(jsonObject: Object, parentKey, carryFormData: FormData): FormData {

    const formData = carryFormData || new FormData();
    let index = 0;

    for (var key in jsonObject) {
        if (jsonObject.hasOwnProperty(key)) {
            if (jsonObject[key] !== null && jsonObject[key] !== undefined) {
                var propName = parentKey || key;
                if (parentKey && this.isObject(jsonObject)) {
                    propName = parentKey + '[' + key + ']';
                }
                if (parentKey && this.isArray(jsonObject)) {
                    propName = parentKey + '[' + index + ']';
                }
                if (jsonObject[key] instanceof File) {
                    formData.append(propName, jsonObject[key]);
                }  else if (jsonObject[key] instanceof FileList) {
                    for (var j = 0; j < jsonObject[key].length; j++) {
                        formData.append(propName + '[' + j + ']', jsonObject[key].item(j));
                    }
                } else if (this.isArray(jsonObject[key]) || this.isObject(jsonObject[key])) {
                    this.convertJsontoFormData(jsonObject[key], propName, formData);
                } else if (typeof jsonObject[key] === 'boolean') {
                    formData.append(propName, +jsonObject[key] ? '1': '0');
                } else {
                    formData.append(propName, jsonObject[key]);
                }
            }
        }
        index++;
    }
    return formData;
}
isArray(val) {
    const toString = ({}).toString;
    return toString.call(val) === '[object Array]';
}

isObject(val) {
    return !this.isArray(val) && typeof val === 'object' && !!val;
}
zmeyuzjn

zmeyuzjn2#

这应该是您的开始--尽管,您需要使其递归化以处理您提到的嵌套FormData。

const shopData = Object.keys(this.shopGroup.value).map(function (key) {
  return encodeURIComponent(key) + '=' + encodeURIComponent(form.value[key]);
}).join('&');
avkwfej4

avkwfej43#

也可以通过以下方式从html-form创建FormData对象:

const formData = new FormData(<HTMLFormElement>document.getElementById('formId'));
zrfyljdw

zrfyljdw4#

解决方案1.最简单的解决方案

formGroupToFormData(formData: FormData, formGroup: FormGroup) {
    for (let key in formGroup.controls) {
        console.log(formGroup.controls[key])
        if (formGroup.controls[key] instanceof FormGroup) {
            this.formGroupToFormData(formData, formGroup.controls[key] as FormGroup);
        }
        else {
            formData.append(key, formGroup.controls[key].value);
        }
    }
}

但是解决方案1不包括FormGroup nested in a FormArray,例如

arryForm: new FormArray([
    this.fb.group({ fff: ['group 1'] }),
    this.fb.group({ fff: ['group 2'] }),
])

解决方案2:覆盖FormArray以及嵌套在FormArray中的FormGroup and FormControl

formGroupToFormData(formData: FormData, formGroup: FormGroup) {
    for (let key in formGroup.controls) {
        if (formGroup.controls[key] instanceof FormGroup) {
            this.formGroupToFormData(formData, formGroup.controls[key] as FormGroup);
        }
        else if (formGroup.controls[key] instanceof FormArray) {
            if ((formGroup.controls[key] as FormArray).controls[0] instanceof FormControl) {
                formData.append(key, (formGroup.controls[key] as FormArray).value);
            }
            else {
                for (let formControl of (formGroup.controls[key] as FormArray).controls) {
                    if (formControl instanceof FormGroup)
                        this.formGroupToFormData(formData, formControl as FormGroup);
                    else {
                        formData.append(key, formControl.value);
                    }
                }
            }
        }
        else {
            formData.append(key, formGroup.controls[key].value);
        }
    }
}
b4wnujal

b4wnujal5#

FormGroupMap到FormData

for (const [key, value] of Object.entries(formGroup.value)) {
    if (typeof value != "object") {
        formData.append(key, String(value))
    }
}

相关问题