Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.4k views
in Technique[技术] by (71.8m points)

angular - How use formData.append for a array in typescript

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.

this are the field in my endpoint:

{
  "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"
    }
  ]
}

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);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

Here is how:

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...