javascriptangularjspromiserestangular

Getting data from Angular Promise


I am trying to get the response of MotorRestangular.all('Motors').getList() assigned to the variable a so I can use it later. The problem is that if I try to access a inside my return function it is undefined. I know that this isn't the correct way to accomplish what I need but I have no clue how do to it any other way.

myApp.factory('Configurations', function(Restangular, MotorRestangular) {
  var a;
  var Motors = function() {
    MotorRestangular.all('Motors').getList().then(function(Motors){
      a = Motors;
    }); 
  }



  return {
    config: function(){
      Motors();
      console.log(a);
      var g = _.groupBy(Motors, 'configuration');
      console.log(g);
      var mapped = _.map(g, function(m) {
        return {

            id: m[0].configuration,
            configuration: m[0].configuration,
            sizes: _.map(m, function(a) {return a.sizeMm})
      }});
    }
  }

});

Solution

  • Please don't use deferred objects. If what you had in your answer worked - then this will work too:

    myApp.factory('Configurations', function (Restangular, MotorRestangular, $q) {
        var getConfigurations = function () {
            return MotorRestangular.all('Motors').getList().then(function (Motors) {
                //Group by Cofig
                var g = _.groupBy(Motors, 'configuration');
                //Map values
                return _.map(g, function (m) {
                    return {
                        id: m[0].configuration,
                        configuration: m[0].configuration,
                        sizes: _.map(m, function (a) {
                            return a.sizeMm
                        })
                    }
                });
            });
        };
    
        return {
            config: getConfigurations()
        }
    
    });
    

    Additionally if an error happens, the returned promise is not left pending forever.