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!

4
  • 1
    You have not returned your promise Commented Aug 27, 2017 at 14:51
  • @harishr Can you please be a little more specific? Commented Aug 27, 2017 at 14:52
  • You have to return your $http call like return $http.get(restURL+var1).then( function(response){ return [].concat(response.data.var2) } ); . But mostly factories should return an object. Commented Aug 27, 2017 at 14:53
  • @Vivz Jesus you're right. My bad. deleting the question! Thank you! :) Commented Aug 27, 2017 at 14:55

1 Answer 1

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;;
        }
    }
});
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, but I prefer to keep it simple :) You were right with your first answer haha, thank you!
I know that it will work with the first method. But I prefer the second method over the first. :)
The second answer is a defer anti-patten and should be avoided. It is unnecessry and prone to erroneous implementation.
@georgeawg Thanks. I didn't know that. :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.