Not able to call angular resource factory save method

74 Views Asked by At

I am using angular resource factory to creates a resource object that let me interact with RESTful server as given below. But when i initiate userService it gives error

TypeError: userService is not a constructor

Factory

angular.module('App')
.factory('userService', function($resource) {
   var user;

  return $resource('/app/user/:id'),{
     'setUser': function (user) {
     this.user=user;
     },

     'getUser': function () {
     return this.user;
     }
     } /// Note the full endpoint address

});

I tried lot of ways but not able to create object. My controller code is

Controller

            $scope.user = new userService(); 
            $scope.user.data = $scope.newUser;
            userService.save($scope.user);

I am missing something?

1

There are 1 best solutions below

2
cody mikol On

EDIT: The answer I originally provided was incorrect. I actually had no idea you could "new" a resource.

It looks like the syntax for defining a resource is not correct, see this example for the AngularJS docs here: https://docs.angularjs.org/api/ngResource/service/$resource

// Define a CreditCard class
var CreditCard = $resource('/users/:userId/cards/:cardId',
  {userId: 123, cardId: '@id'}, {
    charge: {method: 'POST', params: {charge: true}}
});

You are actually returning a resource and an object separated by a comma. In your case is your factory userService is actually just returning

{
     'setUser': function (user) {
     this.user=user;
     },

     'getUser': function () {
     return this.user;
     }
}

And then you are trying to new this.

This is happening because your return is actually using the "comma" operator in javascript separating the actual resource and the object itself. See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator

The comma operator will evaluate each of its operands and return the last one. In this case your actions object.

I don't even think you seed that actions object as to set / get properties of a resource you can just modify the resource properties.

so instead of

$scope.user.$setUser({foo:'bar'});

You can just do

`$scope.user = {foo:'bar'}

If you need to do complex modifications to resources I would instead make services / factories that can modify your resources for you.

tl;dr

change your return to

return $resource('/app/user/:id');

if you really want to add methods to this, you can do so on the prototype

var resource = $resource('/app/user/:id');

resource.prototype.getUser = function(){
  return this.user;
}

return resource;

Sorry for the confusion!