0

I am new to angular framework and have a doubt about structuring my controller.

I have angular controller which makes few service call each of which returns a promise. each call requires (is dependent) data from the previous call.

Even as much as three of such calls converts my controller into an ugly piece of tangled then() embedded in then.

For example consider a scenario of

  1. loading google maps
  2. getting current location of the user
  3. displaying a marker on the map at the current location

The controller is defined as

angular.module('app')
.controller('mapCtrl', ['mapService', function(service){


   var initResult = service.init();
   initResult.then(function(map){
       //01. init succeeded

       var currentLocation = service.currentLocation();
       currentLocation.then(function(currentLocation){

            //02. current location succeeded

            var addMarker = service.addMarker(currentLocation, map);
            addMarker.then(function(){

               //03. added marked

            }, function(){

               //03. failed added marked

            });
       }, function(){
            //02. current location failed -> render some location          

      });


    },
   function(){
       //01. init failed
   });
}]);

the actions were hidden behind a service since I was still not sure if we were going ahead with google maps or open street map or bing.

What I tried state based result object

angular.module('app')
.controller('mapCtrl', ['mapService', function(service){

/* handle add marker*/
var addMarkerResult = {
    success: {},
    failure: {}
};

/* handle get current locations */
var fetchLocationResult = {
    success: function(){ 
        _service.addMarker(addMarkerResult.success, addMarkerResult.failure);
    },
    failure: function(){}
};

/* handle map initialization */
var initMapResult = {
    success: function(){
        _service
          .currentLocation(fetchLocationResult.success, 
                           fetchLocationResult.failure);
    },
    failure: function(){}
};
   service.init().then(initMapResult.success, initMapResult.failure);

}]);

Problem :

  1. Is there a better way of doing this with the code NOT being overpowered with the handling async results ?
  2. Is there a simpler way of doing this which I am not aware of?
4

0 に答える 0