Search code examples
javascriptangularjsangular-resourceangular-promise

Angular $resource - How can I use promise?


How can I use promise with $resource?

This is my service,

     app.service("friendService",function( $resource, $q ) {

        // Return public API.
        return({
            addFriend: addFriend,
            updateFriend: updateFriend,
            getFriends: getFriends,
            removeFriend: removeFriend
        });

        function updateFriend( friend ) {

            var postData = { 
                id: friend.id,
                name: friend.name
            };

            var request = $resource("api/update.php", null,{
                update: { 
                    method:'PUT',
                    data:postData
                }
            });


            return( request.$promise.then( handleSuccess, handleError ) );
        }

I get this error,

TypeError: request.$promise is undefined

What is the correct way doing it with $resource?


Solution

  • Change from

    return( request.$promise.then( handleSuccess, handleError ) );
    

    to

    return request.update().$promise.then(handleSuccess, handleError);
    

    That said, using $resource like this is quite inefficient while not taking any advantage of it. It's better to replace with $http.