双向数据绑定报错’does not exist on type 'any[]'‘

273 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

问题描述

出错代码为:

<span>商品id:{{productionData.products_id}}</span>

控制台报错为:

Property 'products_id' does not exist on type 'any[]'
Error occurs in the template of component ProductionPlanCheckComponent.

曾经的笔记

该字段注释后才可以运行项目,但运行项目后取消注释,页面上可以展示出所调用API中的数据。
查询资料和排除后,发现是因为postman中的basic以及sku并不是数组而是对象。
修改API后的类型发现还是无效,依旧报错。
最后的解决办法,每个span设置为:

<span *ngFor="let c of productionData" [ngValue]="c">商品id:{{c.products_id}}</span>

虽然占位比较多,但是研究了数个小时目前只有这个方法有效,可能会影响性能,后期会进行完善

解决方法

该问题出现的原因为后端给的API传的数组有两层。
例如数组名称叫Array,Array的结构可能为:

Array=[
    ['data1','data2']
    ]

之所以用ngfor可以解决是因为API给的数组里有1个数组,循环1次造成了单次解决的错觉。
后来我的解决方法为:

TS部分:

// 调用API
const url = `planOrder/detail?plan_id=${this.planId}&order_id=${this.orderId}`;
    this.confSvc.sendGetCatch(url, this.isLoading).subscribe(res => {
      // const一个临时数组获取API传过来的数组
      const arrayDataBasic: any[] = res['data'].basic || [];
      // 设置数组orderData为arrayDataBasic数组的第一位
      this.orderData = arrayDataBasic[0];
    });

HTML部分:在HTML中直接调用orderData的字段即可。

<span>计划ID: {{orderData.plan_id}}</span>

这里也可以通过让后端修改的方式解决。

另外一种情况

在详情页面,需要逐步调用数组内的单独字段进行渲染的时候,数组的声明如下:

interface OrderInfo {
  plan_id: number;
  order_id: number;
  order_type_cn: string;
  order_status_cn: string;
  products_sku: string;
  createdTime: string;
  suppliers_id: number;
  receiving_warehouse: number;
  buyer_id: number;
  products_name: string;
  note: string;
}

export class OrderDetailComponent implements OnInit, AfterViewInit {
  // 订单详情数据
  orderDetail: OrderInfo = {
    plan_id: 0,
    order_id: 0,
    order_type_cn: '',
    order_status_cn: '',
    products_sku: '',
    createdTime: '',
    suppliers_id: 0,
    receiving_warehouse: 0,
    buyer_id: 0,
    products_name: '',
    note: '',
  };
}

这样是为了严格控制数组的字段,每次如果新增字段,则需要新添加声明并设置默认值,否则同样会报类似的错误。