如何在Angular中重复这样的列表?特别是有一些属性名称

问题描述 投票:1回答:2

例如,

this.cityService.getCityByCountryId(this.defaultUserNationality, 

    1).subscribe(data => {
          this.cities = data;      
        });

并在html文件中尝试显示如下:

<div class="alert alert-warning">{{cities['0'] | json}}</div>

因为它抛出一个错误:

无法读取未定义的属性“0”

{
  "success": true,
  "remaining_lookups": 9961,
  "0": {
    "id": "4829764",
    "label": "Alabama",
    "value": "4829764",
    "lat": 32.75041,
    "lon": -86.75026,
    "poi_name": "Alabama",
    "parent_id": "6252001",
    "long": -86.75026
  },
  "1": {
    "id": "5879092",
    "label": "Alaska",
    "value": "5879092",
    "lat": 64.00028,
    "lon": -150.00028,
    "poi_name": "Alaska",
    "parent_id": "6252001",
    "long": -150.00028
  },
  "2": {
    "id": "5551752",
    "label": "Arizona",
    "value": "5551752",
    "lat": 34.5003,
    "lon": -111.50098,
    "poi_name": "Arizona",
    "parent_id": "6252001",
    "long": -111.50098
  },
  "3": {
    "id": "4099753",
    "label": "Arkansas",
    "value": "4099753",
    "lat": 34.75037,
    "lon": -92.50044,
    "poi_name": "Arkansas",
    "parent_id": "6252001",
    "long": -92.50044
  }
  "4": {
    "id": "5332921",
    "label": "California",
    "value": "5332921",
    "lat": 37.25022,
    "lon": -119.75126,
    "poi_name": "California",
    "parent_id": "6252001",
    "long": -119.75126
  },
}
json angular typescript ngfor
2个回答
0
投票

正如错误消息所示,cities对象未定义。它只在获取数据后获取值。要解决此问题,您可以为cities对象设置初始值。

class Component{
    public cities = {}; //empty cities object by default. 

    this.cityService.getCityByCountryId(this.defaultUserNationality, 1)
        .subscribe(data => { 
            this.cities = data;
        });
}

如果你想重复Angular的城市列表。您首先必须将其转换为数组。使用Object.keys可以为此工作。


0
投票

你正在做的错误是

<div class="alert alert-warning">{{cities['0'] | json}}</div>

在[]中给出引号,只需使用cities [0]即可得到值

check this image

一旦检查了这张图片,你可以通过城市[$ index]来重复你的项目。

© www.soinside.com 2019 - 2024. All rights reserved.