user66875
user66875

Reputation: 2608

AngularJS service to initialize and get a third party component

I'm building a map-centric application with angularjs and esri arcgis.

I would like to create a seperate service which provides a getMap method that would return the map (after initialized) and an initMap method which does the initialization:

// in my controller:
MapService.initMap();
$scope.map = MapService.getMap();

MapService.js:

angular.module('app')
    .service('MapService',  function($q, esriLoader) {
        var deferred = $q.defer();

        this.getMap = function(){
            if ( angular.isDefined( deferred ) ) return $q.when( deferred );
        }

        var self = this;
        this.initMap = function() {

            esriLoader.require(['esri/Map'],
                function(Map) { 

                    console.log('require callback');

                    // Create the map
                    self.map = new Map({
                        basemap: 'satellite'
                    });


                    console.log('resolve map');

                    deferred.resolve(map);


                });

        }

    });

I get an error on the deferred.resolve(map) line because deferred is undefined.

What am I doing wrong?

Upvotes: 1

Views: 199

Answers (1)

karaxuna
karaxuna

Reputation: 26940

Try this:

this.getMap = function(){
    return deferred.promise;
};

Then use:

MapService.getMap().then(function (map) {

});

Upvotes: 1

Related Questions