如何显示带有索引的数组。我正在从HTTP GET请求中获取数组

时间:2019-06-14 08:39:56

标签: arrays angular

我正在尝试显示类别列表。我使用*ngFor将数组放入ion-list中。我的数组是从HTTP GET请求中获取的。但是来自服务器的数据具有索引,并且我无法显示数组中的所有数据。我已经附上了home.tshome.html以及console.log

home.ts:

  private products = [];
  constructor(private httpClient: HttpClient) {}

  get_products() {
    this.httpClient.get("http://test.vazy.co.ke/api-categories").subscribe((res: any[]) => {
      console.log(res);
      this.products = res["data"];

      console.log(this.products);
      for (var i = 0; i < this.products.length; i++) {
        this.products[i];
      }
    });
  }

home.html:

<button (click)="get_products()">GET /products</button>
<ion-list *ngFor="let product of products">
  <ion-text>
    {{ product[i] }}
  </ion-text>
</ion-list>

2 个答案:

答案 0 :(得分:3)

尝试*ngFor="let product of products; let i of index;"获取索引。

{{ product }}将自动打印索引值。

例如products = [ 'a', 'b', 'c' ];

<ul>
    <li *ngFor="let product of products"> {{ product }} </li>
</ul>

// output
<ul>
    <li> a </li>
    <li> b </li>
    <li> c </li>
</ul>

并且如果您的产品变量包含products = [{ name: 'a', name: 'b', name: 'c' }]

<ul>
    <li *ngFor="let product of products"> {{ product.name }} </li>
</ul>

// output
<ul>
    <li> a </li>
    <li> b </li>
    <li> c </li>
</ul>

根据您的产品输出创建了一个演示

Stackbliz Demo Link

答案 1 :(得分:-1)

<button (click)="get_products()">GET /products</button>
<ion-list *ngFor="let product of products; let i of index;">
<ion-text>
    {{ product[i] }}
</ion-text>
</ion-list>