0

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 ?

AhammadaliPK
  • 3,448
  • 4
  • 21
  • 39

1 Answers1

0

The short answer is: When the constructor is called, there are no visible components yet. Thats why "map" is undefined. Look at the OnInit hook. That's where you want to do these kind of things. Depending on how you implemented everything you might have a chance using Observables. Basically your getMap should return an Observable and your controller subscribes to it in its constructor. Something like:

constructor(){
  self.mapService.getMap()
    .subscribe(map => map.on('moveend', (evt) => {
      //your code here
      }))
}

On a more general note: Why are you wrapping a visible component into a service? Services are not meant for that. You should probably look into creating a Map-Component that wraps OL.

Grmpfhmbl
  • 1,119
  • 12
  • 24