Angular - this.function 不是一个函数[重复]

2023-12-14

我对此有点绝望。我有一个组件,它获取数据并使用该数据的信息渲染地图。这里一切都很好。我在这张地图上放置了标记,我想在标记中执行单击功能。这些函数调用组件中定义的另一个函数,并为我带来数据以在模式中显示它。但是,当我单击标记时,我收到此错误:

this.getInfoAlteracion 不是函数

我不知道为什么。我证明了很多事情,但我看不到错误。这是我的代码:

import { Component, OnInit } from '@angular/core';
import * as L from 'leaflet';
import 'leaflet.markercluster';
import { MapService } from './services';
import * as global from 'app/globals';
import { Alteracion } from './dto/alteracion';

@Component({
  selector: 'map',
  templateUrl: './map.component.html',
  styleUrls: ['./map.component.scss']
})
export class MapComponent implements OnInit {
  public alteraciones: Alteracion[] = [];
  public alteracion: Alteracion[] = [];

  constructor(private mapService: MapService) {}

  ngOnInit() {
    this.getAlteraciones();
  }


  getAlteraciones() {
    this.mapService.getListAlteraciones(11, 1).subscribe(
      result => {
        this.alteraciones = result;
        this.renderMap();
      },
      err => console.log(err)
    );
  }

  getInfoAlteracion(id_alteracion: string) {
    this.mapService.getInfoAlteracion(id_alteracion).subscribe(
      result => {
        this.alteracion = result;
        console.log(this.alteracion);
      },
      err => console.log(err)
    );
  }

  renderMap() {
    L.Icon.Default.imagePath = 'assets/img/theme/vendor/leaflet/';
    let map: any;

      map = L.map('map', {
            zoomControl: false,
            format: 'image/jpeg',
            center: L.latLng(40.4166395, -3.7046087),
            zoom: 2,
            minZoom: 0,
            maxZoom: 19,
            layers: [this.mapService.baseMaps.Esri]});

      L.control.zoom({ position: 'topleft' }).addTo(map);
      L.control.layers(this.mapService.baseMaps).addTo(map);

    let cluster = L.markerClusterGroup();

    for (let al of this.alteraciones) {
      let marker = L.marker([al.coory, al.coorx]);

      marker.on('click', function(e) {
        alert('Id alteración: ' + al.id_alteracion); // THIS WORKS
        this.getInfoAlteracion(al.id_alteracion); // THIS DON'T WORK
        console.log(this.alteracion);
      });

      cluster.addLayer(marker);
    }
    map.addLayer(cluster);   

}

有任何想法吗?提前致谢!


您需要为事件处理程序使用箭头函数

  marker.on('click', (e) => {
    alert('Id alteración: ' + al.id_alteracion); // THIS WORKS
    this.getInfoAlteracion(al.id_alteracion); // THIS DON'T WORK
    console.log(this.alteracion);
  });

在 Javascript 和 Typescript 中this由调用者确定function。箭头函数捕获this从申报网站。很简单this方式不是你所期望的。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular - this.function 不是一个函数[重复] 的相关文章

随机推荐