當頁面加載時,它會從我的 rest api 獲取國家,當用戶選擇一個國家時,它會加載該國家的城市。到目前為止它作業正常,但是當頁面打開時,城市是空的,因為它只有在用戶至少一次選擇一個國家((更改)事件)時才會獲得城市。
為了避免這種情況,我想獲取國家 [] 的第一個元素并在 ngInit 中加載具有國家 ID 的城市。
但如果我想從國家陣列中獲取元素,它總是未定義。我嘗試了多種方法,但我無法讓它作業。
國家型號:
export interface Country{
id: number;
name: string;
}
組件.ts:
countries: Country[] = [];
cities : City[] = [];
loading: boolean = false;
errorMessage: string | undefined;
constructor(
private countryService: CountryServiceService,
private cityService: CityService) {
}
ngOnInit(): void {
this.getCountries();
console.log(this.countries[0]);
}
獲取國家()
public getCountries(){
this.countryService.getCountries().subscribe( response => {
this.countries = response;
}
)
}
HTML:
<select (change)="getCities($event)">
<option *ngFor="let country of countries"
[value]="country.id">
{{country.name}}
</option>
</select>
<select>
<option *ngFor="let city of cities"
[value]="city.id">
{{city.name}}
</select>
uj5u.com熱心網友回復:
有很多方法可以做到這一點。但以你想要的方式。你可以試試下面。
我相信你有getCities(countryId:number)方法。所以就這樣做。
public getCountries(){
this.countryService.getCountries().subscribe( response => {
this.countries = response;
this.fillCities(this.countries[0].id);
}
}
fillCities(id:number){
this.cityService.getCities(id).subscribe( response => {
this.cities=response;
}
}
您需要處理型別檢查/驗證。根據您的要求,上面的代碼是直截了當的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/461790.html
標籤:javascript html 有角度的 打字稿
