Search code examples
angularjsangularjs-serviceangular-resourceangular-servicesangularjs-factory

Should an angularjs $resource be wrapped in a factory? Why not service?


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' }
    });
}]);

Solution

  • 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()