![](/img/trans.png)
[英]How to print the json array values in a list using *ngFor in Angular 2?
[英]How to populate the values in a response object array data using *ngFor in Angular
我想使用 *ngFor 在 Angular 中顯示來自后端 Api 的數據。但是數據是作為一個對象出現的,其中包含一個大小為 10 的數組。這是在console.log(hotels);
中顯示的后端響應的圖像console.log(hotels);
這是我在 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]);
}
});
}
這是我在 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 上運行hotelInfo
。 它應該按照您的回復工作。
例子:
let obj = { responseObj: [ { name: 'a' }, { name: 'b' }, { name: 'c' } ] }; console.log(obj.responseObj);
您可以在 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.