angular - 触发事件时,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);
}
}
}
解决方案
对于 Angular 2+,不要直接使用 leaflet.js 库。相反,请使用优秀的ngx-leaflet
包,它为 Angular 提供 Angular 原生绑定和包装器。按照官方说明进行操作。
如果您是 Angular 2+ 的新手,您可能会发现最初使 ngx-leaflet 工作具有挑战性,但这是完全值得的。
推荐阅读
- javascript - 如何在单个提供者中为多个状态对象实现 React useReducer
- java - Java Jackson 总是将一种类型序列化为另一种类型
- swagger - Swagger json 正在显示不需要的模式,例如 .net 核心 Web api 中的默认对象元数据
- javascript - 有没有办法在不使用画布 API 的情况下从图像文件中获取二进制数据?
- amazon-web-services - 使用 Lambda 将大型 CSV 文件导入 DynamoDB 时出错
- python - 交互式 python 中的意外行为
- python - 使用 python/pandas 将数据框展平并加宽?
- django - Django Rest 框架非空约束
- r - GloVe - R 中的下标越界错误
- python - predict_generator 的输出是什么意思?