首页 > 解决方案 > 如何将 propertiesArray 初始化为数组

问题描述

错误:src/app/services/trades.service.ts:18:32 - 错误 TS7053:元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“对象”。在“对象”类型上找不到具有“字符串”类型参数的索引签名。

18           propertiesArray.push(data[id]);

getAllProperties(){
return this.http.get('data/properties.json').pipe(
  map(data => {
    const propertiesArray: Array<any> = [];
    for (const id in data) {
      if (data.hasOwnProperty(id)){


      propertiesArray.push(data[id]);


    }
    }
    return propertiesArray;
  })
);

}

标签: angular

解决方案


当您的数据始终采用相同格式时,您可以编写类似的内容

// First you define your own interface (make sure its outside of your class)
export interface IProperties {
  Id: number;
  Name: string;
  Salary: number;
}

// Then you map your `data:any` to `data:IProperties[]`
public getAllProperties(): Observable<IProperties[]> {
    return this.http
      .get('data/properties.json')
      .pipe(
        map(data => data as IProperties[])
      );
}

推荐阅读