typescript 类型错误:value.forEach不是FormArray.patchValue中的函数

fquxozlt  于 2023-02-05  发布在  TypeScript
关注(0)|答案(1)|浏览(151)

我收到此错误:

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

我正在从Laravel获取数据,希望这些数据显示在FormArray中。
我的代码如下所示:

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变量(get请求的响应)有这样的对象:

{
   "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:

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

u4vypkhs1#

通过FormArray patchValue的手动操作,它接受数组作为第一个参数:

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

并且错误通知它尝试将value参数用作数组,我假设patchValue的参数应该 Package 在[]
因此,您问题的解决方案应该是:

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

相关问题