我的代码中有一个奇怪的问题。我在类内声明了标记变量,因此它是全局的,并且可以在类内的任何位置访问。但问题是我可以访问 initMap 内部的标记,但无法在 InitMap 的函数内部访问它。错误告诉:TS2339 类型 void 上不存在属性“标记”
export class StudentGraphicReportMapComponent implements OnInit {
locations: any[] = [];
markers:any[] = [];
constructor(private http: Http, private elementRef: ElementRef , private dashboardService: DashboardService) {
}
initMap() {
// ------ CAN ACCESS markers here
this.locations.forEach(function(location: Location) {
for ( let b = 0; b < location.studentCount; b++) {
let marker = new google.maps.Marker({
position: location,
label: 'A'
});
// ----------CANNOT ACCESS markers here
this.markers.push(marker); //Error:Property 'markers' does not exist on type void
}
});
}
ngOnInit() {
this.dashboardService.getStudentCoordinates().then(data => {
this.locations = data.data;
this.initMap();
});
}
}
请帮我解决这个问题。亲切的问候
最佳答案
您应该使用arrow functions像这样访问 this
:
export class StudentGraphicReportMapComponent implements OnInit {
locations: any[] = [];
markers:any[] = [];
constructor(private http: Http, private elementRef: ElementRef , private dashboardService: DashboardService) {
}
initMap() {
this.locations.forEach((location: Location) => {
for ( let b = 0; b < location.studentCount; b++) {
let marker = new google.maps.Marker({
position: location,
label: 'A'
});
this.markers.push(marker); //Error:Property 'markers' does not exist on type void
}
});
}
ngOnInit() {
this.dashboardService.getStudentCoordinates().then(data => {
this.locations = data.data;
this.initMap();
});
}
}
关于javascript - 无法访问 typescript 中的全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45735107/