Search code examples
angularjsangularjs-service

Unset/Set flag of object and persist changes


I am dealing with user objects. My service file:

angular.module('UserService',['ngResource']).factory('User', function($resource){
    var User = $resource('/api/users/:id',
        { 
          list: { method: 'GET' },
          lock: { method: 'PATCH' }
        }
    );   
    return User;
});

The listing of users works well

<div ng:controller="UserController">
    <ul>
        <li ng-repeat="user in users">
            <a ng:click="select(user)">
              {{user.first_name}} {{user.last_name}}
            </a>
        </li>
    </ul>
</div>

And the project file:

var app = angular.module('module-users', ['UserService']);

app.config(function($routeProvider, $interpolateProvider) { 
    $routeProvider.when('/', {
        controller: UserController, 
        templateUrl: Routing.generate('template_user_list')
    });
});


function UserController($scope, User){
    $scope.users = User.query();

    $scope.selectedUser = null;

    $scope.select = function(user){
        $scope.selectedUser = user;
    }

    $scope.lock = function(user){
        user.lock();
        console.log('lock user');
    }
}

However when I want to perform a user lock/unlock I get an error message that the method is unknown. Any ideas whats wrong? How can I perform a lock through the service? Any other suggestions?

TypeError: Object #<Resource> has no method 'lock'

Solution

  • As documentation says:

    The action methods on the class object or instance object can be invoked with the following parameters:

    HTTP GET "class" actions:Resource.action([parameters], [success], [error])

    non-GET "class" actions: Resource.action([parameters], postData, [success], [error])

    non-GET instance actions: instance.$action([parameters], [success], [error])

    Therefore in your case you should call $lock instead of lock

    UPDATE

    Spotted another problem in your code. Action parameters should be given as third parameter, not second. E.g.

    var User = $resource('/api/users/:id',
            {}, //we have no default parameters
            { 
              list: { method: 'GET' },
              lock: { method: 'PATCH' }
            }
        );