问题描述
我正在尝试在Angular 10的HTML表中显示数据,但出现此错误Error trying to diff '[object Object]'. Only arrays and iterables are allowed
。我在下面有这个JSON:
{
"Meta Data": {
"1. Information": "Daily Prices (open,high,low,close) and Volumes","2. Symbol": "petr4.SA","3. Last Refreshed": "2020-10-23","4. Output Size": "Compact","5. Time Zone": "US/Eastern"
},"Time Series (Daily)": {
"2020-10-23": {
"1. open": "20.9400","2. high": "21.1400","3. low": "20.5400","4. close": "20.5700","5. volume": "61328500"
},"2020-10-22": {
"1. open": "20.1000","2. high": "20.8400","3. low": "20.0500","4. close": "20.8400","5. volume": "98359400"
}
}
我的模型班:
export class Candle{
date: Date;
open: string;
high: string;
low: string;
close: string;
volume: string;
}
我的服务等级:
export class CandleService {
constructor(
public http: HttpClient
) { }
findAll(): Observable<Candle[]>{
return this.http.get<Candle[]>(`${API_CONFIG.baseUrl}`);
}
}
最后是HTML:
<div class="container-analyzer">
<table>
<thead>
<th>Date</th>
<th>Open</th>
<th>High</th>
<th>Low</th>
<th>Close</th>
<th>Volume</th>
</thead>
<tbody *ngFor="let candle of ativoData">
<tr>
<td>{{candle.data}}</td>
<td>{{candle.open}}</td>
<td>{{candle.high}}</td>
<td>{{candle.low}}</td>
<td>{{candle.close}}</td>
<td>{{candle.volume}}</td>
</tr>
</tbody>
</table>
</div>
解决方法
您需要一个函数将数据转换为数组,以便可以在模板上显示。
编写这样的函数
transformData(rawData: any) {
let processedData: Array<Candle> = [];
Object.keys(rawData["Time Series (Daily)"] || []).forEach(key => {
processedData.push({
date: new Date(key),open: rawData["Time Series (Daily)"][key]["1. open"],high: rawData["Time Series (Daily)"][key]["2. high"],low: rawData["Time Series (Daily)"][key]["3. low"],close: rawData["Time Series (Daily)"][key]["4. close"],volume: rawData["Time Series (Daily)"][key]["5. volume"]
});
});
return processedData;
}
并在从服务接收到数据后调用它
类似
this.ativoData = this.transformData(this.rawData);
在庙里
<div class="container-analyzer">
<table>
<thead>
<th>Date</th>
<th>Open</th>
<th>High</th>
<th>Low</th>
<th>Close</th>
<th>Volume</th>
</thead>
<tbody *ngFor="let candle of ativoData">
<tr>
<td>{{candle.date | date}}</td>
<td>{{candle.open}}</td>
<td>{{candle.high}}</td>
<td>{{candle.low}}</td>
<td>{{candle.close}}</td>
<td>{{candle.volume}}</td>
</tr>
</tbody>
</table>
</div>
这是工作中的sample
,您可以使用Mat-Angular(材料设计组件)表(https://material.angular.io/components/table/overview)来构建表,而不必编写复杂的代码。您可以轻松地操作要在屏幕上显示的数据。
,我没有看到ativoData的定义,即使它定义了,它也不是数组也不是可迭代的。
您需要获取"Time Series (Daily)"
对象的值并将其转换为数组(可以使用Object.entries()
进行操作)并将其存储到值ativoData
中。
然后,您还需要在HTML的*ngFor
中定义索引以访问每个日期。基本上看起来像*ngFor="let candle of ativoData; index as i"
。
最后,在使用给定索引的插值中,您可以访问如下所示的每个值:
{{candle[i]}} // this will give you the date
{{candle[i].open}} // now you can access each value of the date
{{candle[i].high}}
{{candle[i].low}}
.
.
.
so on and so forth