首页 > 解决方案 > 触发事件时,Angular 下的 Leafletjs 无法访问全局变量

问题描述

对于这个 Angular 项目(我是 Angular 的新手——使用 angular8,我在 AngularJS 上编写了很多代码,但这完全不同)我已经声明了一些全局变量,并且我已经创建了一个传单映射以及 leaflet.draw 插件。地图完美运行。当事件“draw:created”被触发时,我需要访问其中一个全局变量,但我得到了一个未定义的错误(检查 map-base.component.ts 上的注释行)。我做错了什么?我正在尝试遵循推荐的做法并避免使用“窗口”对象。任何想法都非常受欢迎。代码:

全球.ts

import { Injectable } from '@angular/core'
import * as L from 'leaflet';

@Injectable()
export class Globals {
    public L: any;
    public map: any;
    public enableFunc : boolean= true;
    public initZoom: any = 10;
    public initLatLng: any = [39.8, -75.5];
}

map-base.component.ts

import { Component, AfterViewInit } from '@angular/core';
import { Globals } from 'src/global'
import * as L from 'node_modules/leaflet/dist/leaflet-src.js'
import 'src/assets/js/leaflet.draw.1.0.4.min.js'

@Component({
    selector: 'map-base',
    templateUrl: './map-base.component.html'
})
export class MapBaseComponent implements AfterViewInit {
    [x: string]: any;

    constructor(private global: Globals) {
        this.global.L = L;
        L.Browser.touch = true;
    }
    ngAfterViewInit() {
       this.global.map = L.map('map', {}).setView(this.global.initLatLng, this.global.initZoom);
       L.tileLayer('https://cartodb-basemaps-d.global.ssl.fastly.net/rastertiles/voyager_nolabels/{z}/{x}/{y}.png', { attribution: '© CartoDB' }).addTo(this.global.map);

       this.global.map.on('draw:created', function (e) {
           //this line return the object map
           console.log(this)
           //THIS LINE RETURNS ERROR
           console.log(this.global.initZoom);

       }
    }
}

标签: angularleaflet

解决方案


对于 Angular 2+,不要直接使用 leaflet.js 库。相反,请使用优秀的ngx-leaflet包,它为 Angular 提供 Angular 原生绑定和包装器。按照官方说明进行操作。

如果您是 Angular 2+ 的新手,您可能会发现最初使 ngx-leaflet 工作具有挑战性,但这是完全值得的。

https://github.com/Asymmetrik/ngx-leaflet


推荐阅读