0

i have a service witch retrieves users from my backend application, but it returns an empty array when there is some data. Here is code:

var service = this;
service.users = [];
service.getUsers = function()
    {
        $http(
            {
                method: 'GET',
                url: 'http://api.svcassist.dev/index.php/v1/user'
            }
        ).then(
            function( data )
            {
              angular.forEach( data.data.data, function( value, key)
              {
                service.users.push(
                    {
                        id: value.id,
                        first_name: value.first_name,
                        last_name: value.last_name,
                        email: value.email
                    }
                );  
              });
             return service.users;
        },
        function( error ){}
        );
        return service.users;
    };

getUsers() function returns empty array, but when i log data in forEach loop i see that there are some data that are pushed to array. I have a lot more services that works exactly like this, i cant figure out whats wrong here.

  • You may be setting `service.users` to an empty array each time you call it at the beginning...that may be intended or not... – DrCord May 04 '15 at 14:28
  • 1
    You need to move your `return` inside the `then` clause. – Matthew Green May 04 '15 at 14:28
  • @DrCord I can't see anything like that in my code. –  May 04 '15 at 14:30
  • @MatthewGreen I tryed, but then i get undefined –  May 04 '15 at 14:30
  • So then it sounds like you have other issues with your code then. However, the return needs to be in the then so that so that it returns the value asynchronously. Currently, your return is happening before anything is pushed to your array which is why it's always at it's default value. – Matthew Green May 04 '15 at 14:34
  • @MatthewGreen I edited code, is that what you were referrring to? –  May 04 '15 at 14:37
  • Your formatting makes it a little hard to follow but yes that is the idea (minus the original return still being there). The linked question does a good job of explaining what I was saying. – Matthew Green May 04 '15 at 14:40

0 Answers0