我想使用 *ngFor 在 Angular 中显示来自后端 Api 的数据。但是数据是以包含大小为 10 的数组的对象形式出现的。这是 console.log(hotels);
中显示的后端响应的图像。
这是我在 component.ts 文件中编写的 Angular 代码
hotelInfo = [];
hotelInfo2 = [];
getTopHotelInfo() {
const params = [];
params.push({code: 'dateType', name: 'CHECKIN'});
params.push({code: 'fromDate', name: '2018-01-01'});
params.push({code: 'toDate', name: '2019-01-01'});
params.push({code: 'topN', name: 10});
this.dashboardServiceHandler.getTopHotelInfo([], params).subscribe(
hotels => {
console.log(hotels);
this.hotelInfo.push(hotels);
console.log(this.hotelInfo);
for (let i = 0; i < this.hotelInfo.length; i++) {
const hotel = this.hotelInfo[i];
console.log(hotel);
/// this.hotelInfo2.push(hotels[i]);
this.hotelInfo2.push({code: hotel.code, name: hotel.name});
console.log(this.hotelInfo2[i]);
}
});
}
这是我在 component.html 文件中编写的代码
<li *ngFor="let hotel of hotelInfo">
<div class="c-inbox-widget__item">
<div class="c-inbox-widget__item__avatar" style="background: #A3A1FB">
01
</div>
<div>
<span class="c-inbox-widget__item__author">{{hotel.name}}</span>
<!--<span class="c-inbox-widget__item__text">Canada</span>-->
</div>
<div class="c-inbox-widget__item__value">$29,193</div>
</div>
</li>
如何将这些数据作为数组获取到 *ngFor
最佳答案
试试这个方法。您的响应是一个对象,它包含一个带有键 responseObj
的数组。
getTopHotelInfo() {
const params = [];
params.push({code: 'dateType', name: 'CHECKIN'});
params.push({code: 'fromDate', name: '2018-01-01'});
params.push({code: 'toDate', name: '2019-01-01'});
params.push({code: 'topN', name: 10});
this.dashboardServiceHandler.getTopHotelInfo([], params).subscribe(
hotels => {
console.log(hotels);
this.hotelInfo = hotels.responseObj;
});
}
现在在 hotelInfo
上运行 ngFor。它应该按照您的回复工作。
示例:
let obj = {
responseObj: [
{ name: 'a' },
{ name: 'b' },
{ name: 'c' }
]
};
console.log(obj.responseObj);
关于arrays - 如何在 Angular 中使用 *ngFor 填充响应对象数组数据中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60751216/