OGJoshZero OGJoshZero - 4 months ago 8
AngularJS Question

Factory is returning a function instead of the return value of the function in AngularJS

So, I had an application pretty much figured out until I realized that I am making way to many calls to database api and as a result the app is lagging. I am trying to set up a way to keep the current scope accurate when adding and removing items from the $scope object instead of having to request the entire list from the database every time. So I figured from all I've read that a factory is the way to go. That way I can pull the data from the database once, then after successfully adding or deleting entries through the api I can just manipulate the current scope instead of requesting the entire list again. My question is (with an example), How do I fetch a list of users from the api and add that to the scope. Then when I add or delete users from the list I can just remove them from the scope without fetching the list all over again from the api?

Here is my factory:

app.factory("UsersFactory",['Data',function(Data){
var users;

function init(){
Data.get('users')
.then(function (results) {
users = results;
});
}

init();

function getUsers(){
return users;
}

return {
getUsers:getUsers
}

}]);


And after injecting the factory in the controller:

console.log(UsersFactory.getUsers);


This returns the function but not the return value of the function.

I have also tried:

console.log(UsersFactory.getUsers());


Which returns undefined;

I would actually like to do all this in the resolve for the state (ui-router) but in the controller directly is ok too i guess.

Any help would be ap;appreciated and feel free to ask me to clarify anything. I'm not very good at clearly asking questions.

Answer

The correct way to do this is to return a promise from your factory:

app.factory("UsersFactory", ['Data', function(Data) {
  var factory = {
    getUsers: getUsers
  };

  return factory;

  function getUsers() {
    return Data.get('users');
  }
}]);

Then, in your controller:

app.controller("UsersController", ['$scope', 'UsersFactory', function($scope, UsersFactory) {
  function getResponse(response) {
    $scope.users = response.data;
  }

  function getError(response) {
    console.log(response);
  }

  UsersFactory.getUsers()
    .then(getResponse);
    .catch(getError);
}]);
Comments