Vugar Abdullayev Vugar Abdullayev -3 years ago 130
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 =;


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download