Çlirim Kastrati
Çlirim Kastrati

Reputation: 83

TypeError: value.forEach is not a function at FormArray.patchValue

I am getting this error:

ERROR Error: Uncaught (in promise): TypeError: value.forEach is not a function
TypeError: value.forEach is not a function
    at FormArray.patchValue.

I am getting data from Laravel and I want these data to display in a FormArray.

My code looks like this:

this.http.get("http://data_dink" + '/' + event.value)
 .toPromise().then(data => 
 {
    console.log(data);
    this.getSelectedServiceData = data;
    console.log(this.getSelectedServiceData.service);
    this.addForm.get('services').patchValue(this.getSelectedServiceData.service);
 });

data variable (response from get request) has such object:

{
   "msg":"Service Information",
   "service":{
      "id":1,
      "name":"Web Development",
      "description":"Test per web development",
      "price":"200.00",
      "created_at":"2020-05-04T03:07:28.000000Z",
      "updated_at":"2020-05-06T03:07:28.000000Z",
      "view_service":{
         "href":"api\/v1\/service\/1",
         "method":"GET"
      }
   }
}

FormArray built from this object:

{
   "msg":"List of all services",
   "services":[
      {
         "id":1,
         "name":"Web Development",
         "description":"Test per web development",
         "price":"200.00",
         "created_at":"2020-05-04T03:07:28.000000Z",
         "updated_at":"2020-05-06T03:07:28.000000Z"
      },
      {
         "id":2,
         "name":"Java",
         "description":"test per java",
         "price":"100.00",
         "created_at":"2020-05-20T03:07:57.000000Z",
         "updated_at":"2020-05-20T03:07:57.000000Z"
      }
   ]
}

Upvotes: 1

Views: 2174

Answers (1)

num8er
num8er

Reputation: 19372

By manual for FormArray patchValue it accepts array as first argument:

patchValue(
  value:        any[], 
  options: { 
    onlySelf?:  boolean; 
    emitEvent?: boolean; 
  } = {}
): void

and also error informs that it tries to use value argument as an array, I assume that argument for patchValue should be wrapped inside []

so solution to Your question should be:

this.addForm
      .get('services')
      .patchValue(
        [
          this.getSelectedServiceData.service
        ]
      )

Upvotes: 3

Related Questions