我正在 Ionic 2 应用程序上使用 Angular 2 (Typescript)。我有一节课NewFavoriteSitePage
拥有私有(private)属性(property)siteForm
我可以在类方法中使用这个属性,但是当我在一个谷歌地图方法中时,这个变量是未定义的。变量的范围是什么或如何定义从两侧访问的变量?
declare var google;
......
export class NewFavoriteSitePage {
.....
private siteForm: FormGroup;
loadMap(){
//I can access to siteForm here!
.....
google.maps.event.addListener(marker, 'dragend', function(marker, siteForm){
let newlatLng = marker.latLng;
console.log(this.siteForm); //Here this.siteForm is undefined
});
}
最佳答案
之所以没有在那里定义谷歌地图,是因为它是函数的回调,这使得“this”不再等于页面,将其放入变量中可以解决问题。
private siteForm: FormGroup;
loadMap(){
var siteformFromPage=this.siteForm; //this should work
google.maps.event.addListener(marker, 'dragend', function(marker, siteForm){
let newlatLng = marker.latLng;
console.log(siteformFromPage);
});
}
编辑:如果你想要最新的值,你也可以尝试这样:
private siteForm: FormGroup;
loadMap(){
var that=this; //cache that value of the page.
google.maps.event.addListener(marker, 'dragend', function(marker, siteForm){
let newlatLng = marker.latLng;
console.log(that.siteformFromPage);
});
}
关于javascript - typescript 中的范围变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44989849/