0

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

R15
  • 13,982
  • 14
  • 97
  • 173
Vugar Abdullayev
  • 1,852
  • 3
  • 21
  • 46
  • You should check out **this**: https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback (pun intended :P ) – AT82 Aug 17 '17 at 12:31

2 Answers2

4

You should use arrow functions to get access to the this like 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();
    });
  }

}
gilamran
  • 7,090
  • 4
  • 31
  • 50
0

Make local variable points to this

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

and use _self.markers inside function

Anton Lee
  • 684
  • 4
  • 10