Search code examples
angularjsangularjs-serviceangularjs-resource

AngularJS: don't remove data until resource loads


I'm completely new to $resource so I'm not sure how to use it.

(this is not the real code but it is similar)

service:

.factory('User', function ($resource) {
            return $resource(apiPath + 'user/:id', {}, {
                query: {method: 'GET', isArray: true}
            })
        })

controller:

$scope.showUser = function(userID){
    $scope.user = User.get({id:userID});
}

view:

<button ng-click="showUser(user.id+1)">Show user</button>

<h1>{{user.name}}</h1>

It works great, but every time I press the button, the user's name disappears and then appears when the data is returned - $scope.user becomes empty until the next user is loaded. I don't want that, I want the old user to remain until the next user is loaded. Thanks.


Solution

  • You can specify a callback function, which will be executed when the resource has been fetched.

     // Not assigning the return value here on the scope ...
    
     User.get({ id: userID}, function(user) {
    
          // ... but rather here when the call has completed.
    
          $scope.user = user;
    
     });
    

    See the $resource documentation for more info.