Search code examples
angularjsangular-resource

AngularJS $resource update/ PUT operation?


I'm confused as to how exactly to update a resource using $save. I've read the angular resource documentation and looked at other posts on stack overflow but I cannot seem to perform an update operation on an existing object.

For example, I have an event object and I want to update its name and location properties. I have the start of a function that correctly takes in the eventId of a singular event.

Here is the function so far:

 eventService.updateEvent = function (eventId, eventName, eventLocation) {

   // Defines the resource (WORKS)
   var Event = $resource('/api/events/:id/', {id:'@_id'});

   // Gets the event we're talking about (WORKS)
   var event = Event.get({'id': eventId});

   // TODO update event

  };

How do i successfully update this resource?


Solution

  • Figured it out!

    When I defined the resource, I defined the PUT operation as a custom method called 'update'.

    I called get on that resource and looked up a particular object by ID. Using a promise, I was able to update the resource using the 'update method' if the object was found, else throw an error.

    eventService.updateEvent = function (eventId,eventName,eventLocation) {
    
         // Define the event resource, adding an update method
         var Event = $resource('/api/events/:id/', {id:'@_id'},
         { 
             update: 
             {
                method: 'PUT'
             }
        });
    
        // Use get method to get the specific object by ID
        // If object found, update. Else throw error
        Event.get({'id': eventId}).$promise.then(function(res) {
           // Success (object was found)
    
           // Set event equal to the response
           var e = res;
    
           // Pass in the information that needs to be updated
           e.name = eventName;
           e.location = eventLocation;
    
           // Update the resource using the custom method we created
           Event.update(e)
    
        }, function(errResponse) {
           // Failure, throw error (object not found)
           alert('event not found');
       });
    
    };