Monday, December 16, 2013

how to make a $resource service in AngularJS

angular.module('widgetsServices', ['ngResource'])
   .factory('Widgets', function($resource, $http) {
      var resource = $resource('./widgets/:id', {id: "@id"},
      {
         update: {method:'PUT'}
      });
      return resource;
   });

 
 

With that under our belt, note that this...

Widgets.save(order, function(data) {
   var orderId = data.pKey;
   $state.transitionTo("viewWidget", {id: orderId});
}, widgetControllers.reportServiceError);

 
 

...and this...

Widgets.update(order, function(data) {
   var orderId = data.pKey;
   $state.transitionTo("viewWidget", {id: orderId});
}, widgetControllers.reportServiceError);

 
 

...are examples of how to, from a controller, hit the widgetsServices defined at the top of this blog posting. The services then use RESTful routing to hit a backend such as that suggested here. Notice that we have to explictly define the "update" but not the "save" at the top of this blog posting. That is because the save is a given per this which suggests the following will always be available:

  1. get
  2. save
  3. query
  4. remove
  5. delete

 
 

$stateParams.id is another fascinating bit of AngularJS magic that I do not yet understand. It gave me the id of the current object (Widget) which I needed at a CRUD screen for editing a Widget (so that I might update the appropriate record at the database). Clearly, "$stateParams" and "Widgets" need to be in a controllers signature for this magic (above) to work.

No comments:

Post a Comment