如何在Angular中重复这样的列表?尤其是带有多个性质的名称

时间:2018-09-07 05:55:26

标签: json angular typescript ngfor

例如,

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
  },
}

2 个答案:

答案 0 :(得分:0)

如错误消息所示,cities对象未定义。一旦获取数据,它只会获得一个值。要解决此问题,您可以为“城市”对象设置一个初始值。

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

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

如果要重复Angular中的城市列表。您首先必须将其转换为数组。使用Object.keys可以解决这个问题。

答案 1 :(得分:0)

您正在犯的错误是

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

在[]中给出引号,您只需使用城市[0]即可获取值

check this image

一旦检查此图像,并重复进行一次您可以通过城市[$ index]实现的项目。