Chathruaka Waas
Chathruaka Waas

Reputation: 351

Error when accessing a AngularJs service method which uses $resource

i'm new to angularjs and trying to access a service method which uses $resource to make a call to my rest api. But when i'm trying to access its giving a error. also when i try to access a method which does not use $resource it works fine.

here's my code.

app.factory('userService', ['$resource',
    function($resource) {        
        var factory = {};

        factory.authenticatedUser;

        factory.test = function(){
            return "Test";
        };

        factory.getLoggedInUser = function(){ 
            $resource('api/user', {}, {
                query: {method: 'GET'}
            });
        };

        factory.getAuthenticatedUser = function(){
                return factory.authenticatedUser;
        };

        factory.setAuthenticatedUser = function(user){
                factory.authenticatedUser = user;
        };

        return factory;
    }]);

here's how i'm trying to access the method.

userService.getLoggedInUser.query(function(loggedInUser) { 

});

this throws the following error.

TypeError: userService.getLoggedInUser.query is not a function 

but this works fine.

var text = userService.test(); 

What am i doing wrong here?

Upvotes: 0

Views: 64

Answers (1)

Rickard Staaf
Rickard Staaf

Reputation: 2740

You need to add a $ sign. And return the $resource object from your function

factory.getLoggedInUser = function(){ 
        return $resource('api/user', {}, {
            query: {method: 'GET'}
        });
    };

userService.getLoggedInUser().$query(function(loggedInUser) { 
});

Upvotes: 1

Related Questions