I have a mapservice(maps.service.ts) , in which I've wrote some code for loading the map , like this ,
loadMap(target: string, extent?: number[], proj?: string) {
var self = this;
this._mapExtent = !extent ? [372728.74434305, 2677793.4448, 378257.6623, 2682126.61080438] : extent;
this.projection = proj || this.projection;
this._map = new OlMap({
layers: [
new OlTileLayer({
source: new olSourceOSM()
}),
// layerWFS
],
target: target,
view: new OlView({
center: this._mapExtent,
projection: this.projection,
maxZoom: 19,
zoom: 13
})
});
return new Promise((resolve, reject) => {
this._map.once('postrender', function (map) {
self.isMapLoaded = true;
resolve(map);
})
});
//return this._map.once('postrender').map(res => res.json());
}
and a getMap()
method to get map instance throughout the app ,
getMap() {
return this._map;
}
But in another controller , inside the constructor , I need to subscribe map change event , like this ,
constructor(){
self.mapService.getMap().on('moveend', (evt) => {
if (self.undoRedo === false) {
if (self.size < self.navHistory.length - 1) {
for (var i = self.navHistory.length - 1; i > self.size; i--) {
self.navHistory.pop();
}
}
self.navHistory.push({
extent: self.mapService.getMap().getView().calculateExtent(self.mapService.getMap().getSize()),
size: self.mapService.getMap().getSize(),
zoom: self.mapService.getMap().getView().getZoom()
});
self.size = self.size + 1;
}
});
}
but the problem is , constructor is loading before map loaded and map
is getting undefined
, could anyone please suggest a best practice for this scenario? do i need to make getMap() method to return promise and call getMap().then() always ?