For this Angular project (I'm new to Angular --using angular8, I coded a lot on AngularJS but this is totally different) I have declared some global variables and I've created a leaflet map along with the leaflet.draw plugin. The map works perfect. When the event 'draw:created' is fired, I need access to one of those global variables, but instead I get an undefined error (check commented line on map-base.component.ts). What I'm doing wrong? I'm trying to follow the recommended practices and avoid the use of the 'window' object. Any idea very welcome. code:
global.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);
}
}
}