【问题标题】:Populate countries from json file to angular2-multiselect将国家/地区从 json 文件填充到 angular2-multiselect
【发布时间】:2020-07-28 05:13:17
【问题描述】:

我想尝试从 json 文件 url 加载国家/地区:https://raw.githubusercontent.com/sagarshirbhate/Country-State-City-Database/master/Contries.json 到 angular2-multiselect。下面是我的代码

getCountries(){
this.country.allCountries().
subscribe(
    data2 => {
      this.countryInfo = data2.Countries.CountryName;
      console.log('Data:', this.countryInfo);
    },
    err => console.log(err),
    () => console.log('complete')
 )
}

所以 getcountry 函数从我用 url 创建的服务获取数据,这里是服务

  export class CountriesService {
  url: string = "https://raw.githubusercontent.com/sagarshirbhate/Country-State-City- 
  Database/master/Contries.json";

  constructor(private http: HttpClient) { }

 allCountries(): Observable<any>{
  return this.http.get(this.url);
 }
 }

此显示数据:在控制台日志中未定义。请帮我解决它

【问题讨论】:

  • 先试试“this.countryInfo = data2.Countries;” & 检查你是否得到一个数组。
  • 请问console.log你的data2好吗?我们可以得到服务的实际响应。
  • @MohanRajput 我在控制台获取数据是正确的,但这给了我完整的 json 数据列表,但我只需要 json 中的 countryName
  • 所以我猜你需要循环data2.Countries数组,然后你会得到countryList。 data2.Countries[0].CountryName, data2.Countries[1].CountryName.... data2.Countries[n].CountryName
  • 为你的代码创建 stacblitz。

标签: javascript angular multi-select


【解决方案1】:

使用以下代码获取CountryName

getCountries(){
 this.countryInfo = [];
this.country.allCountries().
subscribe(
    data2 => {
     
        data2.Countries.forEach(element => {
          this.countryInfo.push(element.CountryName);
        });
      console.log('Data:', this.countryInfo);
    },
    err => console.log(err),
    () => console.log('complete')
 )
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-30
  • 1970-01-01
  • 2019-12-16
  • 1970-01-01
  • 2011-01-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多