首页 > 解决方案 > 如何以角度遍历JSON数组

问题描述

在我的 Angular 应用程序中,我使用 api 来获取有关所选国家/地区的数据。

我无法让我的应用程序显示响应数据中语言部分的名称属性,如下所示:

[{
    "name": "Colombia",
    "topLevelDomain": [".co"],
    "alpha2Code": "CO",
    "alpha3Code": "COL",
    "callingCodes": ["57"],
    "capital": "Bogotá",
    "altSpellings": ["CO", "Republic of Colombia", "República de Colombia"],
    "region": "Americas",
    "subregion": "South America",
    "population": 48759958,
    "latlng": [4.0, -72.0],
    "demonym": "Colombian",
    "area": 1141748.0,
    "gini": 55.9,
    "timezones": ["UTC-05:00"],
    "borders": ["BRA", "ECU", "PAN", "PER", "VEN"],
    "nativeName": "Colombia",
    "numericCode": "170",
    "currencies": [{
        "code": "COP",
        "name": "Colombian peso",
        "symbol": "$"
    }],
    "languages": [{
        "iso639_1": "es",
        "iso639_2": "spa",
        "name": "Spanish",
        "nativeName": "Español"
    }],
    "translations": {
        "de": "Kolumbien",
        "es": "Colombia",
        "fr": "Colombie",
        "ja": "コロンビア",
        "it": "Colombia",
        "br": "Colômbia",
        "pt": "Colômbia"
    },
    "flag": "https://restcountries.eu/data/col.svg",
    "regionalBlocs": [{
        "acronym": "PA",
        "name": "Pacific Alliance",
        "otherAcronyms": [],
        "otherNames": ["Alianza del Pacífico"]
    }, {
        "acronym": "USAN",
        "name": "Union of South American Nations",
        "otherAcronyms": ["UNASUR", "UNASUL", "UZAN"],
        "otherNames": ["Unión de Naciones Suramericanas", "União de Nações Sul-Americanas", "Unie van Zuid-Amerikaanse Naties", "South American Union"]
    }],
    "cioc": "COL"
}]

我曾尝试使用管道、嵌套的 *ngFor 循环,但在显示语言名称方面没有运气。有什么建议么?

在我的模板中,我使用以下 HTML 和插值来显示国家对象的名称:如何使用类似的方法来访问响应数据语言中的名称属性?

             <div>
                <label>Country Capital:</label>
                <p>{{ country.capital }} </p>
            </div>

我的应用程序由 3 个模块、1 个父组件 (CountryComponent) 和两个子组件 (CountryListComponent) 和 (CountryDetailComponent) 组成。使用 eventEmmiter 将数据从 List 组件发送到 Detail 组件。我对 Country 类型使用以下模型:

 export interface Country {

      name: string;
topLevelDomain?: string[];
alpha2Code?: string;
alpha3Code?: string;
callingCodes?: string[];
capital?: string;
altSpellings?: string[];
region?: string;
subregion?: string;
population?: number;
latlng?: number[];
demonym?: string;
area?: number;
gini?: number;
timezones?: string[];
borders?: string[];
nativeName?: string;
numericCode?: string;
currencies?: Currency[];
languages?: Language[];
translations?: Translation;
flag?: string;
regionalBlocs?: Regional[];
cioc?: string;

}

在我的列表组件中,我使用以下内容使用服务类获取数据并初始化 Country 类型的国家数组,并使用 eventEmmiter 将国家对象发送到 Detail 组件:

 public countries: Country[];
  getCountries(){
    this.countryService
      .getCountries()
      .subscribe((data: any) => {
        this.countries = data;
      },
      error => {console.log('error loading')});
  }
  @Output() selectedCountry = new EventEmitter<Country>();

列表组件模板:

<li class="list-group-item" 
            highlightDirective 
            style="cursor: pointer;
                text-align: center;
                font-family:'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif;"
            *ngFor="let country of countries | searchFilter: searchText : 'name'" (click)="onCountrySelected(country)">
            {{ country.name }}
        </li>

在 Detail 组件中,我收到事件:

@Input() country: Country;

在详细模板中我试图显示它:

    <h2> {{ country.name }} </h2>
        <br>
        <div class="row" #countrySelected>
            <div class="col-sm">
                <label>Country Capital:</label>
                <p>{{ country.capital }} </p>
                <p>{{ country.languages.name }}</p>
            </div>
            <div>

我使用 eventEmmiter 将 Country 对象从 List 组件发送到使用父组件的 Detail 组件,父模板如下:

<div class="row"
style="padding-left: 20px;
        padding-right: 20px;">
    <div class="col-xs-5">
        <app-country-list (selectedCountry)="childEventClicked($event)"></app-country-list>
    </div>
    <div class="col-xs-7">
        <app-country-detail [country]="(selectedCountryEvent)"></app-country-detail>
    </div>
</div>

标签: javascripthtmlangular

解决方案


鉴于每个对象都包含在一个数组中,我假设每个属性可以包含多个对象作为值。您可以尝试以下方法。

我将来自 API 的响应分配给一个名为countries.

控制器

countries = [];

getData() {
  this.apiService.getCountries().subscribe(
    response => { this.countries = response; },
    error => { // handle error }
  );
}

模板

<div *ngFor="let country of countries">
  <label>Country Capital:</label>
  <p>{{ country.capital }} </p>
  <label>Languages:</label>
  <p *ngFor="let language of country.languages">{{ language.name }}</p>
  <label>Currencies:</label>
  <p *ngFor="let currency of country.currencies">{{ currency.name }}</p>
</div>

更新

接口定义存在问题。该languages属性被定义为一个类型数组,string而它是一个自定义对象。您可以为每种类型的对象定义一个单独的接口。尝试以下

export interface Country {
  name: string;
  topLevelDomain?: string[];
  alpha2Code?: string;
  languages?: Language[];
  currencies?: Currency[];
  translations?: Translate[];
  regionalBlocs?: RegionalBloc[];
  .
  .
  .
}

export interface Language {
  iso639_1:? string;
  iso639_2:? string;
  name:? string;
  nativeName:? string;
}

其他属性也是如此currenciestranslationsregionalBlocs。每个都需要自己的接口定义,类似于此处显示的languages.


推荐阅读