2017-08-17 1 views
0

J'ai un problème étrange dans le code. J'ai déclaré des marqueurs variables à l'intérieur d'une classe afin qu'elle soit globale et accessible partout dans la classe. Mais le problème est que je peux accéder aux marqueurs dans initMap mais je ne peux pas y accéder à l'intérieur de la fonction de InitMap. L'erreur indique: TS2339 La propriété 'marqueurs' n'existe pas sur le type videImpossible d'accéder à la variable globale de type

  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(); 
    }); 
    } 

} 

Aidez-moi à résoudre ce problème. Kind regards

+0

Vous devriez vérifier out ** this **: https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback (jeu de mots: P) – Alex

Répondre

3

Vous devez utiliser arrow functions pour obtenir l'accès au this comme ceci:

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(); 
    }); 
    } 

} 
+0

merci c'est aussi utile! –

0

Faire des points variables locales à ce

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

et utiliser _self.markers dans la fonction

+0

Oui cela a bien fonctionné. Merci. –