javascript - 无法访问 typescript 中的全局变量

标签 javascript angular typescript ecmascript-6 typescript2.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();
    });
  }

}

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

最佳答案

您应该使用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();
    });
  }

}

关于javascript - 无法访问 typescript 中的全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45735107/

相关文章:

javascript - "TypeError: can' t 将未定义转换为对象“仅在 vite 构建之后,之前,使用 vide dev,一切正常

javascript - 在预期返回 void 的函数参数中返回 Promise

TypeScript 条件类型扩展对象,仅可用属性

javascript - 根据数字使用 Javascript 更改文本颜色

javascript - 如果值为负,Highcharts 将数据标签与 x 轴对齐

javascript - 用户未登录时 Wordpress AJAX 返回 0

javascript - SEO:如何索引来自客户端 api 请求的数据

javascript - 在 Dart 中 .callMethod 返回后如何调用 .then?

angular - 当仅知道名称时从 Injector 接收管道

使用 CORS 在 IIS 上运行的 Angular 2 和 .net 核心 Web 应用程序之间的 HTTP 415 OPTIONS 请求