2017-08-17 94 views
0

我在代碼中出現了一個奇怪的問題。我在類中聲明標記是可變的,所以它是全局的,並且可以在類內部的任何地方訪問。但問題是我可以在initMap中訪問標記,但不能在InitMap的函數中訪問它。錯誤告訴:TS2339屬性「標記」不存在類型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(); 
    }); 
    } 

} 

請幫我解決這個問題。親切的問候

+0

您應該檢查出**這**:https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback(雙關語意:P) – Alex

回答

3

您應該使用arrow functions獲得訪問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(); 
    }); 
    } 

} 
+0

謝謝,這也有幫助! –

0

使本地變量指向此

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

,並使用_self.markers內部功能

+0

是的,這工作很好。謝謝。 –