2017-08-17 66 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

是的,这工作很好。谢谢。 –