Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Html 如何在Angular中从JSON中的列表中获取值?_Html_Json_Angular - Fatal编程技术网

Html 如何在Angular中从JSON中的列表中获取值?

Html 如何在Angular中从JSON中的列表中获取值?,html,json,angular,Html,Json,Angular,我需要从这个JSON获取城市内部的值,但我不能: { "id":0, "department":"Amazonas", "cities":["Leticia","Puerto Bayarta",] }, { "id":1, "department":"Antioquia", "cities":[

我需要从这个JSON获取城市内部的值,但我不能:

{ 
"id":0,
"department":"Amazonas",
"cities":["Leticia","Puerto Bayarta",]
},
{ 
"id":1,
"department":"Antioquia",
"cities":["Medellin","Bello",]
}
以下是我制作的组件和服务:

城市服务

组件有一个接口:

nueva-organizacion.component.ts

最后,我想在选择器中显示城市:

Choose one...
Leticia
Puerto Bayarta
Medellin
Bello
nueva-organizacion.component.html

但我明白了:

Choose one...
Leticia, Puerto Bayarta
Medellin, Bello
也许正确的方法是使用索引{city.cities[]}},但我不知道如何使用。

ngOnInit():void{
这个城市
.getJSON(
'https://raw.githubusercontent.com/marcovega/colombia-json/master/colombia.min.json'
)
.订阅((res:any)=>{
这是1.cities=[];
foreach(在res中输入){
foreach(花旗进入城市){
这个.城市.推动(花旗);
}
}
});
}

在这一侧,您有一个条目数组,其中包含一个城市数组。您需要首先将ans中的所有城市夷为平地,类似于上面的代码。我的代码不准确,但应该能让您了解编写内容。

请记住,在NuevaOrganizacionComponent中,您必须使用相同名称的属性:“cities”,首先是cities数组,其次是cities服务

此外,我建议您使用两个选项而不是一个,第一个选项选择部门,第二个选项选择城市

代码如下所示:

nueva Organization.component.ts:

从'@angular/core'导入{Component,OnInit};
从'src/app/services/cities.service'导入{CitiesService};
@组成部分({
选择器:“app nueva organizacion”,
templateUrl:'./nueva organizacion.component.html',
样式URL:['./nueva organizacion.component.css'],
})
导出类NuevaOrganizacionComponent实现OnInit{
公共部门R=[]
所选公共部门:any=null;
选择的公共城市:any=null;
建造师(
公共城市服务,
) {}
ngOnInit():void{
康斯特城市=”https://raw.githubusercontent.com/marcovega/colombia-json/master/colombia.min.json"
this.citiesServ.getJSON(urlCities)
.订阅((res:any)=>{
this.departmentsArr=res;
});
}
getCities(){
返回this.departmentsArr.find(department=>department.id==this.departmentSelected).ciudades
}
alertSelection(){
const departmentName=this.departmentsArr.find(department=>department.id==this.departmentSelected).departmento;
const cityName=this.citySelected;
警觉的(`
您选择了部门:${departmentName}和城市:${cityName}`)
}
}
<div class="form-input">
   <select id="city" class="custom-select">
      <option selected>Choose one...</option>
      <option *ngFor="let city of cities">
         {{ city.cities }}
      </option>
   </select>
</div>
Choose one...
Leticia
Puerto Bayarta
Medellin
Bello
Choose one...
Leticia, Puerto Bayarta
Medellin, Bello