[英]How to populate the values in a response object array data using *ngFor in Angular
I want to display data coming from a backend Api in Angular using *ngFor.But data is coming as an object which contains an array of size 10.This the image of the backend response that shows in console.log(hotels);
我想使用 *ngFor 在 Angular 中显示来自后端 Api 的数据。但是数据是作为一个对象出现的,其中包含一个大小为 10 的数组。这是在console.log(hotels);
中显示的后端响应的图像console.log(hotels);
This is the angular code which i have written in component.ts file这是我在 component.ts 文件中编写的角度代码
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]);
}
});
}
This is the code which i have written in component.html file这是我在 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>
How could I get those data as an array to *ngFor我如何将这些数据作为数组获取到 *ngFor
Try this way.试试这个方法。 your response is an object and it contains an array with key responseObj
.您的响应是一个对象,它包含一个带有键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;
});
}
Now run ngFor on hotelInfo
.现在在 hotelInfo 上运行hotelInfo
。 It should work as per your response.它应该按照您的回复工作。
Example:例子:
let obj = { responseObj: [ { name: 'a' }, { name: 'b' }, { name: 'c' } ] }; console.log(obj.responseObj);
You could use keyValue pipe in angular您可以在 angular 中使用keyValue管道
<div *ngFor="let hotel of hotelInfo">
<div *bgFor="let q of hotel | keyvalue>
{{q.key}} - {{q.value}}
</div>
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.