我在代碼中出現了一個奇怪的問題。我在類中聲明標記是可變的,所以它是全局的,並且可以在類內部的任何地方訪問。但問題是我可以在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