我用ngx-leaflet和ngx-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()方法,但再次捕获错误。
Uncaught :无法读取未定义的属性“打开”
注意:,当我在onMapReady()外部尝试这个方法时,如果没有ngx-leaflet,它就会工作得很好。
发布于 2020-05-17 14:54:48
我找到问题并解决了它。在这里,我在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);
}
}
https://stackoverflow.com/questions/61746311
复制相似问题