首页 > 解决方案 > 单击 ngx-leaflet 中的标记后,材质对话框未打开

问题描述

我正在使用ngx-leafletngx-leaflet-draw显示传单地图。我可以从工具栏标记图标在地图上显示一个标记。当我单击标记时,我想显示一个材质对话框组件。单击标记时,我可以在控制台上显示标记坐标。代码是

public onMapReady(map: L.Map) {
    map.on(L.Draw.Event.CREATED, function(e) {
      const type = (e as any).layerType,
        layer = (e as any).layer;

      if (type === 'marker') {
        const markerCoordinates = layer._latlng;
        layer.on('click', () => {
          console.log(markerCoordinates); // works properly
        });
      }
    });
  }

然后我尝试修改显示材质对话框组件的代码但得到错误

import { NgZone } from '@angular/core';
import { MatDialog, MatDialogRef } from '@angular/material/dialog';
import { MaterialDialogComponent } from './m-dialog.component';
...
...
export class NgxLeafletComponent {
  dialogRef: MatDialogRef<MaterialDialogComponent>;

  public constructor(private zone: NgZone) {}

  public onMapReady(map: L.Map) {
      map.on(L.Draw.Event.CREATED, function(e) {
        const type = (e as any).layerType,
          layer = (e as any).layer;

        if (type === 'marker') {
          const markerCoordinates = layer._latlng;
          layer.on('click', () => {
            console.log(markerCoordinates); 
            this.zone.run(() => this.onClickMarker()); //error
          });
        }
      });
    }

  onClickMarker() {
    this.dialogRef = this.dialog.open(MaterialDialogComponent);
  }
 }

错误输出:错误控制台输出

我也尝试这个没有zone.run()方法,直接dialog.open()方法但再次捕获错误

未捕获的类型错误:无法读取未定义的属性“打开”

注意: 当我尝试这种外部onMapReady()方法并且没有ngx-leaflet它时,它完全可以正常工作。

标签: angularleaflettypeerrorngx-leafletmaterial-dialog

解决方案


我得到了问题并解决了它。map.on(L.Draw.Event.CREATED, function(e) {...}在这里,我使用了不允许另一个函数调用的常规函数​​() 。所以它需要箭头函数来调用其中的另一个方法/函数。

import { NgZone } from '@angular/core';
import { MatDialog, MatDialogRef } from '@angular/material/dialog';
import { MaterialDialogComponent } from './m-dialog.component';
...
...
export class NgxLeafletComponent {
  dialogRef: MatDialogRef<MaterialDialogComponent>;

  public constructor(private zone: NgZone) {}

  public onMapReady(map: L.Map) {
      map.on(L.Draw.Event.CREATED, (e) => {
        const type = (e as any).layerType,
          layer = (e as any).layer;

        if (type === 'marker') {
          const markerCoordinates = layer._latlng;
          layer.on('click', () => {
            console.log(markerCoordinates); 
            this.zone.run(() => this.onClickMarker()); //error
          });
        }
      });
    }

  onClickMarker() {
    this.dialogRef = this.dialog.open(MaterialDialogComponent);
  }
 }


推荐阅读