arrays - 如何在 Angular 中使用 *ngFor 填充响应对象数组数据中的值

标签 arrays angular spring typescript object

我想使用 *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/

相关文章:

c - 原地反转数组

php - 遍历 Mysql 表实际上是如何工作的?

c++ - 错误 : no match for 'operator&&'

java - 如何使用 RestTemplate 向相对 URL 发送 POST 请求?

javax.validation 不存在

spring - Apache Tomcat 设置 java.lang.NoClassDefFoundError : org/springframework/asm/ClassVisitor

VB.NET 谓词数组查找

javascript - 如何在 Angular 2 Typescript 中为 FormBuilder 对象设置值

angular - 如何将表达式作为 Angular2 中的输入传递给组件?

javascript - Angular - 在调整大小时更改 html 元素