我在代码中出现了一个奇怪的问题。我在类中声明标记是可变的,所以它是全局的,并且可以在类内部的任何地方访问。但问题是我可以在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();
});
}
}
请帮我解决这个问题。亲切的问候
您应该检查出**这**:https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback(双关语意:P) – Alex