2

why a $resource should be used by .factory? and why .service is a wrong way?

e.g.

app.factory('Notes', ['$resource', function($resource) {
return $resource('/notes/:id', null,
    {
        'update': { method:'PUT' }
    });
}]);

why is it wrong?

app.service('Notes', ['$resource', function($resource) {
return $resource('/notes/:id', null,
    {
        'update': { method:'PUT' }
    });
}]);
ya_dimon
  • 3,483
  • 3
  • 31
  • 42
  • 1
    The second one would work fine, but only because JavaScript has this weird feature of allowing a constructor function to return an object, instead of just initializing `this`and returning it. Since you don't really won't to construct an object, but instead want to return one, a factory make more sense. – JB Nizet May 04 '16 at 16:29

1 Answers1

1

Both are singletons, but services are instantiated using the new keyword. You won't be able to access the static class methods of $resource if you're going to use service which, depending on your application may be better.

In other words you won't be able to use:

Notes.query({ ... });
Notes.create({ ... });

and other class function variants. Only instance methods such as:

note.$get()
note.$save()
note.$update()
Muli Yulzary
  • 2,559
  • 3
  • 21
  • 39