My goal:
Build an AngularJS service (MapService
) which initializes (MapService.initMap()
) a 3rd party control (Esri ArcGIS Map) and return a reference to my map (MapService.getMap()
) so I can use it in all my controllers.
Code
<!DOCTYPE html>
<html ng-app="app">
<body ng-controller="MapController">
<script data-require="angular.js@1.5.0" data-semver="1.5.0" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js"></script>
<script defer type="text/javascript" src="//js.arcgis.com/4.0beta3/"></script>
<script src="angular-esri-loader.js"></script>
<script src="script.js"></script>
</body>
</html>
Script.js:
(function(angular) {
'use strict';
var app = angular.module('app', ['esri.core']);
angular.module('app')
.controller('MapController', function(esriLoader, $scope, MapService) {
MapService.getMap().then(function (mapObj) {
console.log("resolved!!!"); // this code is never reached
alert('show map');
$scope.map = mapObj;
});
MapService.initMap();
});
angular.module('app')
.service('MapService', function($q, esriLoader) {
this.deferred = $q.defer();
this.getMap = function(){
return this.deferred.promise;
}
var self = this;
this.initMap = function() {
// self.deferred.resolve('test'); // When I uncomment this line, the promise will be successfully resolved and the 'then' runs
esriLoader.require([
'esri/Map',
'esri/widgets/Search',
'esri/widgets/Search/SearchViewModel'
]).then(function(esriModules){
var Map = esriModules[0];
var Search = esriModules[1];
var SearchViewModel = esriModules[2];
// Create the map
var map = new Map({
basemap: 'satellite'
});
console.log("resolve map"); // this code is reached, however, it still doesn't seem to correctly resolve the promise
self.deferred.resolve(map);
});
}
});
})(angular);
Plunkr
https://plnkr.co/edit/LEhYqHVSpscTZ5kJCfyJ
The problem:
The promise which getMap()
returns is never resolved, so the code within MapService.getMap().then()
is never reached.
When I resolve the promise with some test string (self.deferred.resolve('test');
) in my initMap()
method, it works.
So I suppose it's a problem of the 'esriLoader.require()' method which is another promise resolved after require
ing some dependencies of the map component.
So I'm basically resolving a promise within a promise. I added the code of the esriLoader to plunkr.
What am I doing wrong?