我从ws正确获取所有城市,但是当我在其他过滤城市使用时是空数组。请关注我的代码。
client: Client;
cities: City[] = [];
selectedCity: string;
filteredOptionsCity: any;
city_id: FormControl = new FormControl();
myform: FormGroup;
constructor(public fb: FormBuilder) {
this.myform = this.fb.group({
'city_id': new FormControl('', Validators.required),
'client_name': new FormControl('', Validators.required),
'email': new FormControl('', Validators.required)
});
}
ngOnInit() {
this.populateForm();
this.ws.allcity().subscribe(
cities => {
this.cities = cities.map((city) => {
return new City(city);
});
console.log(cities) //return all my city correctly
}
);
this.filteredOptionsCity = this.city_id.valueChanges.pipe(
startWith(''),
map(value => this.filterCity(value))
);
this.selectedCity = this.cities.filter(
x => x.city_id === this.client.city
.map(x => x.city_id)[0])
.map(y => y.name).join('')
console.log(this.cities) //cities are empty
}
}
populateForm() {
this.activatedRoute.params.subscribe(
params => {
this.ws.getClientById(params['id']).subscribe(
client => {
this.client = client;
this.patchForm();
}
);
}
);
}
patchForm() {
this.myform.controls['client_name'].setValue(this.client.clientName);
this.myform.controls['email'].setValue(this.client.email);
this.myform.controls['city_id'].setValue(this.client.city);
}
filterCity(val: string): City[] {
if (val) {
let filterValue = val.toString();
return this.cities.filter(city => city.name.toString().startsWith(filterValue));
}
return this.cities;
}
我想过滤城市,我尝试过滤,但在此代码中,我的城市是空的。
this.selectedCity = this.cities .filter(
x => x.city_id === this.client.city
.map(x => x.city_id)[0])
.map(y => y.name).join('')
console.log(this.cities ) //cities are empty
}
我有一个例子,这个逻辑运行良好,但是当我使用来自ws的数据时,这对我不起作用。 DEMO Example