AngularJS $资源更新/ PUT 操作?

AngularJS $resource update/ PUT operation?

我对如何使用 $save 更新资源感到困惑。我已阅读 angular 资源文档并查看了有关堆栈溢出的其他帖子,但我似乎无法对现有对象执行更新操作。

例如,我有一个事件对象,我想更新它的名称和位置属性。我有一个函数的开始,它正确地接受了单个事件的 eventId。

到目前为止的功能如下:

 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

  };

如何成功更新此资源?

想通了!

当我定义资源时,我将 PUT 操作定义为一个名为 'update' 的自定义方法。

我对该资源调用了 get 并按 ID 查找了特定对象。 使用承诺,如果找到对象,我可以使用 'update method' 更新资源,否则会抛出错误。

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

};