Search code examples
angularmultipartform-dataangular4-httpclient

Send Array in Multipart/formdata in angular 7


I am trying to send a JSON array inside formdata and also, other form fields with it. This Json array's fields are generated dynamically. However, it is giving me error 500.

This is how i have to send.

[{"sabha_id":9,"followup_id":1},{"sabha_id":8,"followup_id":24}]

This is my formArray.

   sabhaArray: this.formBuilder.array([
    this.formBuilder.group({
      sabha_id: [''],
    sabha_type: [''],
    followup_id: ['']
    })
  ])

This is my form append request.

 fd.append("major_subject", this.registerForm.get("major_subject").value);
  fd.append("company_name", this.registerForm.get("company_name").value);
  fd.append("profile_picture", this.selectedFile, this.selectedFile.name);
  fd.append("sabha_details", JSON.stringify(this.registerForm.get("sabhaArray")));
  this.contactService.addYuvak(fd).subscribe(
    res => {
      this.router.navigate(["pages/contact"]);
    },
    err => {
      console.log(err);
    }
  );
}

This is my Service which is making post request.

addYuvak(fd:FormData): Observable<Yuvak> {
    const addYuvakURL = this.rooturl + 'createcontact';
    console.log(fd);
    var headers = new HttpHeaders();
   // headers.append('Content-Type',);
    //let body = JSON.stringify(yuvak);
   // let fd = new FormData();
    return this.http.post<Yuvak>(addYuvakURL, fd).pipe(
      tap((yuvak: Yuvak) => console.log(`added yuvak w/ id=${yuvak.id}`)),
      catchError(this.handleError<Yuvak>('addYuvak'))
    );
  }

Solution

  • you are using sabhaArray directly. You need to get value of the array.

    try this:

    `fd.append("sabha_details", JSON.stringify(this.registerForm.get("sabhaArray").value));`