1

I'm new to angularjs, and I know there are a lot of questions regarding this error, Unfortunately I couldn't find an answer that fits my problem in any of them.

I've got a factory that holds all the functions, and controllers that use them. in one controller I got a GET function that returns an array, most of my functions are written almost the same, as well as functions that's written exactly the same like this one, only with different variables names/url, but this error occurs only with this function:

Controller:

$scope.getAllFunction = function(){
         appServicesProvider.getAll($scope.var1).then(function(res){
             $scope.var2 = res;
         })
     };

Factory (appServicesProvider) :

   function getAll(var1){
            $http.get(restURL+var1).then(
                    function(response){
                        return [].concat(response.data.var2)
                    }
            );
        }

As I said, there are more functions that's written exactly the same, only this one won't work, which makes it harder for me to solve. Appreciate any help given!

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Dor Golan
  • 169
  • 1
  • 1
  • 13

1 Answers1

1

You have to return the promise

  function getAll(var1){
           return $http.get(restURL+var1).then(
                    function(response){
                        return [].concat(response.data.var2)
                    }
            );
        }


Or you can rewrite your factory to return an object containing your resolved promise using $q
app.factory('appServicesProvider', function() {
    return {
        getAll: function(var1) {
            var defer = $q.defer();
            $http.get(restURL + var1).then(function(response) {
                defer.resolve([].concat(response.data.var2));
            }).catch(function(response, status) {
                defer.reject(response.data.message);
            });
            return defer.promise;;
        }
    }
});
Vivz
  • 6,625
  • 2
  • 17
  • 33
  • 1
    Thanks, but I prefer to keep it simple :) You were right with your first answer haha, thank you! – Dor Golan Aug 27 '17 at 15:14
  • I know that it will work with the first method. But I prefer the second method over the first. :) – Vivz Aug 27 '17 at 15:18
  • 1
    The second answer is a [defer anti-patten](https://stackoverflow.com/questions/30750207/is-this-a-deferred-antipattern) and should be avoided. It is unnecessry and prone to erroneous implementation. – georgeawg Aug 27 '17 at 16:22
  • @georgeawg Thanks. I didn't know that. :) – Vivz Aug 27 '17 at 17:12