无法在typescript中访问全局变量

时间:2017-08-17 12:27:07

标签: javascript angular typescript ecmascript-6 typescript2.0

我在代码中遇到了一个奇怪的问题。我在类中声明了标记变量,因此它是全局的,可以在类中的任何地方访问。但问题是我可以访问initMap中的标记但不能在InitMap的函数内访问它。错误告诉:TS2339类型void

上不存在属性'markers'
         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();
    });
  }

}

请帮我解决这个问题。亲切的问候

2 个答案:

答案 0 :(得分: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();
    });
  }

}

答案 1 :(得分:0)

将局部变量指向此

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

并在函数

中使用_self.markers