【问题标题】:Cant acces a variable from inside a function of an event listener / Angular 2无法从事件侦听器/Angular 2的函数内部访问变量
【发布时间】:2018-02-17 11:37:48
【问题描述】:

我正在使用 google maps api v3 并且在我的地图上有一些多边形。我正在尝试添加一个事件,在单击时将它们全部删除并在事件的回调函数中调用另一个函数,但我不断收到 TypeError: Cannot read property 'length' of undefined on line 64(这在事件侦听器内部及其告诉我的 Polys 数组未定义)。此外,如果我尝试在侦听器中添加一个函数,它不会识别它,我认为它与范围问题有关,但我不知道如何解决它。 提前感谢您的帮助。

export class InicioComponent implements OnInit, AfterViewInit {

  locaciones: Locacion[] = [];
  regiones: Region[];
  polys: any[] = [];
  constructor(private locacionService: LocacionService, private router: Router) { }

  getLocaciones(): void {
    this.locacionService.getLocaciones().then(locaciones => this.locaciones = locaciones);
  }

   public loadLocaciones(router: Router) {
    for (let i = 0; i < this.locaciones.length; i++) {
      const marker = new google.maps.Marker({
        position: new google.maps.LatLng(this.locaciones[i].latitud, this.locaciones[i].longitud),
        map: map,
        label: {
          color: 'black',
          fontWeight: 'bold',
          text: this.locaciones[i].nombre,
        },
        idLocacion: this.locaciones[i].id
      });
      google.maps.event.addListener(marker, 'click',() => {
        router.navigate(['/locacion', this.locaciones[i].id]);
      });
    }
  }
  getRegiones() {
    this.locacionService.getRegiones().then(regiones => {
      this.regiones = regiones;
      console.log(this.regiones);
    });
  }
  loadRegiones(regiones: Region[]) {
    for(let i = 0; i < regiones.length; i++) {
      const p = new google.maps.Polygon({
        paths: regiones[i].mapData.bounds,
        strokeColor: '#FF0000',
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillColor: '#FF0000',
        fillOpacity: 0.35,
        idRegion: regiones[i].id
      });
      p.setMap(map);
      this.polys.push(p);
      google.maps.event.addListener(p, 'click', function(event){
        for( let j = 0; j < this.polys.length; j++) {
        this.polys[j].setMap(null);
        }
        this.loadLocaciones();

      });
    }
  }

【问题讨论】:

标签: angular google-maps scope


【解决方案1】:

您需要使用箭头函数()=&gt;,而不是function 关键字。当您使用function 关键字时,您将范围扩大到this。将您的代码更改为:

google.maps.event.addListener(p, 'click', (event) => {
    for( let j = 0; j < this.polys.length; j++) {
        this.polys[j].setMap(null);
    }
    this.loadLocaciones();
  });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-17
    • 1970-01-01
    • 1970-01-01
    • 2018-11-28
    • 1970-01-01
    • 2020-01-18
    • 2019-12-20
    相关资源
    最近更新 更多