Vugar Abdullayev Vugar Abdullayev - 5 months ago 37
TypeScript Question

Cannot access global variable in typescript

I have a weird problem in the code. I declared markers variable inside a class so it is global and can be accessed everywhere inside class. But the problem is that I can access markers inside initMap but cannot access it inside function of InitMap. Error tells: TS2339 Property 'markers' does not exist on type 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();
});
}

}


Please help me to solve this problem. Kind regards

Answer Source

Make local variable points to this

initMap() { 
let _self = this;
...
}

and use _self.markers inside function