我收到一个错误,我的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在上一页上调用时被初始化,所以这不应该是问题。此外,当我在代码中没有表单构建器时,我没有任何问题。由于checkIfValidCity函数,该问题确实出现了。
你知道这是从哪里来的以及如何解决它吗?
多谢!
构造函数之外的方法会丢失类的上下文,因此使用"this"将表示方法,而不一定是类。如果您希望方法使用类的上下文,则需要将其绑定到构造函数中。
加 this.checkIfValidCity = this.checkIfValidCity.bind(this)
到您的构造函数。