Material 单击 ngx-leaflet 中的标记后对话框未打开

Material Dialog not open after clicking on marker in ngx-leaflet

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

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
        });
      }
    });
  }

然后我尝试修改显示Material对话框组件的代码,但出现错误

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() 方法但再次捕获错误

Uncaught TypeError: Cannot read property 'open' of undefined

注意: 当我在 onMapReady() 方法之外尝试这个并且没有 ngx-leaflet 它工作得很好。

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

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);
  }
 }