0

I've created a Factory to retrieve customers:

customerModule.factory("CustomerFactory", ["$http", "DataService", function ($http, dataService) {

    var self = this;
    self.page = 1;
    self.query = "";

    var queryFn = function (query) {
        self.query = query;
        $http.get(dataService.baseURI + "/customers", {
            params: {
                query: self.query,
                page: self.page,
                pageSize: 50
            }
        }).success(function (data) {
            return data.result;
        });
    };

    return {
        query: queryFn
    };
}]);

But when I use it in my controller, it returns undefined, I'm not sure what I'm doing wrong here?

$scope.$watch("query", function () {
    if ($scope.query && $scope.query.length > 3) {
        console.log(customerFactory.query($scope.query));
    }
    else if ($scope.query.length < 4) {
        $scope.customers = [];
    }
});
2
  • queryFn returns nothing, and JS keyword for "nothing" is undefined. Commented Nov 30, 2013 at 23:29
  • But I thought return data.result would be returned? Or at least, that is what I want to be returned Commented Nov 30, 2013 at 23:32

1 Answer 1

1

If you take a close look at your queryFn function you will notice that you're not actually returning anything from it. This means that queryFn will return undefined.

So the first step to fixing your code is to put return in front of $http.

Second step is fixing the way you are calling customerFactory.query function. You expect it to return the value immediately, but $http actually creates an XHR request, and XHR requests are async by default, so you cannot expect customerFactory.query to return the result right away.

If you haven't learned of promises than this is the time to take a look at them, because they are used all over the place, in angular world.

Assuming that you have put return in front of $http, the call to customerFactory.query will actually return a promise object. That promise object has a .then method. This method should be used as:

customerFactory.query($scope.query)
  .then(function(customers){
    console.log(customers);
  });
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.