如何在打字稿中将formData.append用于数组 [英] How use formData.append for a array in typescript

查看:73
本文介绍了如何在打字稿中将formData.append用于数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想向我的端点配置文件发送一个表单,我的问题出在字段用户:{},因为我找不到将数组放入此字段的方法.

Hi i want to send a form to my endpoint Profile, my problem is in the field user:{}, because i can't find the way to put my array into this field.

这是我端点中的字段:

{
  "id": 4,
  "ci": "123456",
  "photo": "http://127.0.0.1:8000/media/profiles/12809632_10208569440535095_617453747387788113_n_zAUAVMf.jpg",
  "phone_number": "+59177621589",
  "user": {
    "id": 5,
    "username": "sdanderson",
    "first_name": "ssss",
    "last_name": "ssss"
  },
  "experience": "null",
  "typeskill": [
    {
      "id": 1,
      "skill_name": "developer"
    }
  ]
}

这是我提出PUT请求的服务:

And here is my service for make a PUT request:

putProfile(id:string,token:string,body:any,files:any):Observable<Profile>{

//save data to send to the endpoint for update
    let formData: FormData = new FormData();

    for (let file of files) {
        formData.append('photo', file);
    }
    formData.append('ci',body['ci']);  
    formData.append('phone_number', body['phone_number']); 
    formData.append('experience',body['experience']);
    formData.append('user',body['user']);//here i have inside the fields: body['user'].id,body['user'].first_name,body['user'].last_name





    //include header
    let headers = new Headers();
    headers.append('Accept', 'application/json');
    headers.append("Authorization","Token "+ token);

    return this.http.put(this.api+"profile/"+id+'/',formData,{headers})
        .map(this.extractData)
        .catch(this.handleError);
}

推荐答案

FormData的 append()方法只能接受 string blob 类型.如果需要附加数组,请使用 JSON.stringify()方法将数组转换为有效的JSON字符串.

FormData's append() method can only accept objects of string or blob type. If you need to append the array, use JSON.stringify() method to convert your array into a valid JSON string.

方法如下:

formData.append('user', JSON.stringify(body['user']));

此处,您可以阅读更多有关JavaScript的JSON对象.

Here you can read more about JavaScript's JSON object.

这篇关于如何在打字稿中将formData.append用于数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆