Hi,

I am using ngResource for API calls. There are 2 approaches in our team and 
I would like to know which one is the best :


   - First way
   
service.js
(function() {
  'use strict'

  angular.module('felix')
  .factory('ConversationService', ConversationService);

  ConversationService.$inject = ['$resource'];

  function ConversationService($resource) {
    var Conversation;

    Conversation = 
$resource("http://0.0.0.0:3000/conversations/:id/:action";, { id: "@id", action: 
"@action" },
      {
        trash: {
          method: 'PUT',
          params: {
            action: 'trash'
          }
        }
      }
    );

    return Conversation;
  };
})();

controller.js calls
// retrieve
vm.conversation = ConversationService.get(42);

// call put method
vm.conversation.$trash();

This one has the avantage to be able to use the custom actions on single 
resource (as $trash, $read, $update, etc)


   - Second way 
   
service.js
(function() {
  'use strict'

  angular.module('felix')
  .factory('ConversationService', ConversationService);

  ConversationService.$inject = ['$resource', '$q'];

  function ConversationService($resource, $q) {
    var current_conversation = null,
        resource = 
$resource('http://0.0.0.0:3000/conversations/:id/:action', {id: '@id', 
action: '@action'});

    var Conversation = {
      current_conversation: current_conversation, // null on init
      find: find // promise
    };

    return Conversation

    // --- Functions --- //

    function find(id) {
      var deferred = $q.defer();
      if (id) {
        resource.get({ id: id }).$promise.then(function(result) {
          deferred.resolve(result);
        });
      }
      return deferred.promise;
    }

    function trash(id) {
      var deferred = $q.defer();
      if (id) {
        resource.get({ id: id, action: 'trash' 
}).$promise.then(function(result) {
          deferred.resolve(result);
        });
      }
      return deferred.promise;
    }
  };
})();

controller.js
// retrieve
vm.conversation = {
'id': '',
'title': ''
};

ConversationService.find(42).then(function(result) {
 vm.conversation = result;
});

// call put method
ConversationService.trash(vm.conversation.id);


-- 
You received this message because you are subscribed to the Google Groups 
"AngularJS" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.

Reply via email to