angular - 如何在角度数组类型的变量中设置响应?
问题描述
我想将响应数据存储在来自 API 响应的变量中,并将其显示在 component.html 文件中。
组件.ts 文件:
public coinsHistory = [];
this.service.getCoinsHistory().subscribe(
(response) => {
this.handleCoinsResponse(response);
},
(error) => {
console.log(error);
}
);
handleCoinsResponse(response: any) {
console.log('what ------', response);
this.spinner.show();
if (response.status === 1) {
this.coinsHistory = response.responseData.data;
console.log(' this.coinsHistory ------', typeof(this.coinsHistory));
}
}
在 component.html 文件中:
<div *ngFor="let coinData of coinsHistory">
<p>{{ coinData.coins_earned_for }}</p>
<p>{{ coinData.referral_coins }}</p>
</div>
来自api的数据是这样的:
status: 1
msgCode: 224
msg: "Referrer coins history"
responseData:
total_coins: 200
data: Array(2)
0:
id: 85
referrer_id: 4
referee_id: null
coins_earned_for: "Deducted for withdraw"
referral_coins: "-100"
created_at: "2020-02-01 12:18:21"
updated_at: "2020-02-01 12:18:21"
1:
id: 85
referrer_id: 4
referee_id: null
coins_earned_for: "Deducted for withdraw"
referral_coins: "-100"
created_at: "2020-02-01 12:18:21"
updated_at: "2020-02-01 12:18:21"
但我得到错误说:
Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
解决方案
尝试使用模型而不是任何模型来定义响应,例如:
export interface ICoinsHistory{
totalCoins: number;
data: ICoin[];
}
export interface ICoin{
//...Coin data
}