angular - 如何将 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;
})
);
}
解决方案
当您的数据始终采用相同格式时,您可以编写类似的内容
// 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[])
);
}
推荐阅读
- python - 从 Python 中的字符串中删除列表中的模式
- sql - 使用 NULL 作为通配符的 SQL “重复数据删除”
- apache - Apache 2.4 太多重定向,www 到非 www 和 http 到 https
- excel - 如何定位从特定行开始的每第 n 行以更改字体颜色和样式?
- javascript - discord.js 列出具有一定作用的频道
- javascript - 变量不包含对“this”的引用
- multithreading - 在 Python 中从线程向主发出 g_signal
- html - 为什么我的元素比指定高度高 4px?
- stream - Google Nearby 连接 - 无法在 2 个设备之间传输大字节
- javascript - 对象中的扩展语法如何工作?