Reputation: 2085
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
Upvotes: 0
Views: 2681
Reputation: 694
Make local variable points to this
initMap() {
let _self = this;
...
}
and use _self.markers
inside function
Upvotes: 0
Reputation: 7294
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();
});
}
}
Upvotes: 4