[AngularJS] $resource

$resource Refactor

Let's convert our custom Note factory to use Angular resource. Removeall()find(), and create() methods from our Note service and replace them with the $resource equivalent.

angular.module('NoteWrangler')
.factory('Note', ['$http', function NoteFactory($http) {
  
  return {
    all: function() {
      return $http({method: 'GET', url: "/notes"});
    },
    find: function(id) {
      return $http({method:'GET', url: '/notes/' + id});
    },
    create: function(noteObj) {
      return $http({method: 'POST', url: '/notes/', data: noteObj});
    }
  };
}]);

Include angular-resource.js in index.html so that we can use it in our app. It is located in the same directory as our angular.js file.

<script src="./js/vendor/angular-resource.js"></script>

 

Replace the existing object that is returned from the Note factory with an Angular resource that uses '/notes' as the data source.

angular.module('NoteWrangler')
.factory('Note', ['$resource', function NoteFactory($resource) {
  return $resource("/notes");
}]);

 

Using a $resource-ful Note Service 

Now that our Note factory is using ngResource, we'll need to update how it's used in NotesIndexController.

angular.module('NoteWrangler')
.controller('NotesIndexController', ['$scope', 'Note', 'Tweetable', function($scope, Note, Tweetable) {
  Note.all().success(function(data) {
    $scope.notes = data;
  });
  
  $scope.tweetThatNote = function(noteToTweet) {
    Tweetable(noteToTweet).success(function(status) {
      console.log(status);
    });
  };
}]);

 

Replace the existing call to Note.all() with the correct call to the NoteAngular resource.

//before
  Note.all().success(function(data) {
    $scope.notes = data;
  });

//now
$scope.notes = Note.query();

 

 A Custom Method for Our Note $resource

Wouldn't it be great to have a custom method on our Note resource to mark it as tweeted?

Add a tweetIt method to the Note resource. Remember, this updates an existing note, so use the correct HTTP method.

angular.module('NoteWrangler')
.factory('Note',['$resource', function NoteFactory($resource) {
  return $resource('/notes', {}, {
    tweetIt : {
      method: 'PUT'
    }
  });
}]);

 

posted @ 2015-03-05 04:00  Zhentiw  阅读(462)  评论(0编辑  收藏  举报