第一个盒子效果很好。但是第二个不起作用。他们彼此依赖。而且错误不会出现。
我没有其他尝试,因为它没有任何错误。
city.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class CityService {
constructor(private http:Http) { }
getCitys(){
return this.http.get("http://localhost:3003/api")
.map(response => response.json());
}
}
city.ts
export interface City
{
name: string,
value:number,
down: Down[]
}
export interface Down
{
name: string,
value:number,
places: Places[]
}
export interface Places
{
name: string;
pname:string;
unvan: string
}
city.component.ts
@Component({
selector: 'app-city',
templateUrl: './city.component.html',
styleUrls: ['./city.component.css']
})
export class CityComponent implements OnInit {
cityDatas: [];
downDatas: [];
placesDatas: [];
constructor(private cityService: CityService) { }
ngOnInit() {
this.cityService.getCitys().subscribe(d => {
this.cityDatas = d;
this.downDatas = d.down;
this.placesDatas = d.places });
}
}
city.component.html
<select [(ngModel)]="selectedData">
<option [ngValue]="null" selected disabled>First</option>
<option *ngFor="let data of cityDatas" [value]="data">
{{ data.name }}
</option>
</select>
<select [(ngModel)]="selectedDw" >
<option [ngValue]="null" selected disabled>Second</option>
<option *ngFor="let dw of downDatas" [value]="dw">
{{dw.name}}
</option>
</select>
和api json
[
{"name":"City1",
"value":1,
"down":
[{"name":"Down11",
"value":101,
"places":
[{"name":"Place111",
"pname":"JustPlace",
"unvan":"center"
},
{"name":"Place112",
"pname":"Jp",
"unvan":"center"
}]
},
{"name":"Down12",
"value":102,
"places":
[{"name":"Place121",
"pname":"Jp",
"unvan":"side"
},
{"name":"Place122",
"pname":"Jp",
"unvan":"side"
}]
}
]
},
{"name":"City2",
"value":2,
"down":
[{"name":"Down21",
"value":103,
"places":
[{"name":"Place211",
"pname":"Jp",
"unvan":"center"
},
{"name":"Place212",
"pname":"Jp",
"unvan":"center"
}]
},
{"name":"Down22",
"value":104,
"places":
[{"name":"Place221",
"pname":"JustPlace",
"unvan":"side"
},
{"name":"Place222",
"pname":"Jp",
"unvan":"side"
}]
}
]
}
]
当我选择第一个时,我希望第二个工作。我想要显示结果。但是我无法运行第二个选择框,控制台也没有给出任何错误。 为什么不起作用?它将如何工作?
答案 0 :(得分:1)
downDatas
是undefined
,因为订阅中的d
是array
,而不是object
。尝试以这种方式实现它(在第一个选择中选择selectedData
之后,第二个数据将可用):
<select [(ngModel)]="selectedData">
<option selected disabled>First</option>
<option *ngFor="let data of cityDatas; index as i;" [value]="i">
{{ data.name }}
</option>
</select>
<select [(ngModel)]="selectedDw" >
<option [ngValue]="null" selected disabled>Second</option>
<option *ngFor="let dw of cityDatas[selectedData]?.down" [value]="dw">
{{ dw.name }}
</option>
</select>
答案 1 :(得分:0)
您需要实施城市选择标签的change
事件并为downDatas更新datasource
onChange($event, cityid) {
let selectedcity = this.cityDatas.filter(c=>c.value == cityid)[0];
console.log(JSON.stringify(selectedcity))
this.downDatas = selectedcity.down;
}
HTML
<select [(ngModel)]="selectedData" #city (change)="onChange($event, city.value)">
演示https://stackblitz.com/edit/angular-city-down?file=src/app/app.component.ts