我收到一个错误,我的this.worldCities未定义,并且我无法使用以下代码对其进行查找
export class SelectCityModalPage {
worldCities : Array<City>;
chosenCity:City;
myForm;
constructor(public navCtrl: NavController, public navParams: NavParams,
public appCitiesProvider:AppCitiesProvider, public viewCtrl:ViewController,
public formBuilder:FormBuilder) {
this.worldCities = this.appCitiesProvider.worldCities;
this.chosenCity = new City();
this.chosenCity.name = "";
console.log("In modal the world cities are " + this.worldCities);
this.myForm = formBuilder.group({
cityControl: ['Start typing...', this.checkIfValidCity]
//cityControl:['']
});
}
ionViewDidLoad() {
console.log('ionViewDidLoad SelectCityModalPage');
}
closeModal(){
this.chosenCity = this.worldCities.find((element) =>{
return element.name == this.chosenCity.name;
});
this.viewCtrl.dismiss(this.chosenCity);
}
checkIfValidCity(control : FormControl){
let validation = this.worldCities.find((element) => {
return element.name == control.value;
});
return validation != undefined;
}
}
我的提供者就是这样:
export class AppCitiesProvider {
errorMessage;
worldCities:Array<City>;
constructor(public http: Http, errorHandler:ErrorHandler) {
console.log('Hello Cities Provider');
this.getWorldCities2()
.subscribe(
(cities) => {
this.worldCities = cities;
console.log("in provider the worldCities are " + this.worldCities);
},
(error: any) => this.errorMessage = <any>error);
;
}
getWorldCities2() {
return this.http.get('../assets/city.list.json')
.map(res => res.json());
}
}
我不明白的是appCitiesProvider.worldCities在上一页调用时已初始化,所以这不应该是问题。 此外,当我在代码中没有formbuilder时,我没有任何问题。由于checkIfValidCity函数,问题确实出现了。
你知道它来自何处以及如何解决它?
非常感谢!
答案 0 :(得分:1)
构造函数外部的方法会丢失类的上下文,因此使用&#39; this&#39;将意味着方法,而不一定是班级。如果希望方法使用类的上下文,则需要在构造函数中绑定它。
添加
this.checkIfValidCity = this.checkIfValidCity.bind(this)
到你的构造函数。