【问题标题】:Angular 7 export json data into HTML table. Element name contains dash(-)Angular 7 将 json 数据导出到 HTML 表中。元素名称包含破折号 (-)
【发布时间】:2019-09-15 09:44:22
【问题描述】:

我正在从我无法控制的第 3 方 api 中获取一些 json 格式的数据。数据是这样返回的。

        "Hotel": "SponsoredInterContinental Marine Drive",
        "Best-price": "US$\u00a0378US$\u00a0180InterContinental",
        "vendor3-price": "US$378",
        "vendor1": "Expedia.com",
        "vendor1-price": "US$181",
        "vendor2": "Booking.com",
        "vendor2-price": "US$257",
        "vendor3": "Cancelon"

我能够将数据输出到我的 html 表中,但某些键的名称中有破折号(-)。当我尝试使用

访问元素时,这会导致我的打字稿出现问题
  <ng-container matColumnDef="best_price">
    <th mat-header-cell *matHeaderCellDef class="table-header"> Best Price </th>
    <td mat-cell *matCellDef="let element"> {{element.Best-price}} </td>
  </ng-container>

我只得到该索引返回的空白数据,但在 Observable 数组中肯定有数据。我创建了一个使用蛇大小写键声明的可观察对象,但我无法访问该元素。如何访问数组的“最佳价格”键。

可观察对象

export interface Room {
    hotel: string;
    best_price: string;
    vendor_1: string;
    vendor_2: string;
    vendor_3: string;
    vendor_1_price: string;
    vendor_2_price: string;
    vendor_3_price: string;
}

组件打字稿

export class RoomsComponent implements OnInit {


  displayedColumns: string[] = ['hotel', 'best_price', 'vendor_1', 'vendor_2', 'vendor_3', 'vendor_1_price', 'vendor_2_price', 'vendor_3_price'];
  dataSource: Room[];

  constructor(private roomsService: RoomsService) { }

  ngOnInit() {
    this.getRooms();
  }

  getRooms(): void {
    this.roomsService.getRooms().subscribe(
      data => { this.dataSource = data['comparison'] },
      err => console.error(err),
      () => console.log('done loading rooms'));

    // this.dataSource = this.roomsService.getRooms()['comparison'];
    console.log(this.dataSource);
  }
}

【问题讨论】:

  • 我认为您可以使用 rxjs map 函数来映射您的响应,以便在它进入您的模型之前删除破折号

标签: html angular typescript html-table


【解决方案1】:

尝试使用{{element["Best-price"]}} 访问,看看是否可行。可以使用字符串键访问对象中的属性。

【讨论】:

    【解决方案2】:

    尝试{{element['Best-price']}} 而不是{{element.Best-price}}

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-25
      • 1970-01-01
      • 2022-09-28
      • 1970-01-01
      • 2012-08-31
      • 2015-03-27
      • 2021-04-03
      • 2016-03-18
      相关资源
      最近更新 更多