AngularJS $资源更新/ PUT操作?

时间:2016-06-16 18:39:39

标签: angularjs angular-resource

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

例如,我有一个事件对象,我想更新其名称和位置属性。我有一个正确接受奇异事件的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

  };

如何成功更新此资源?

1 个答案:

答案 0 :(得分:0)

想出来了!

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

我打电话给那个资源,用ID查找一个特定的对象。 使用promise,如果找到对象,我可以使用'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');
   });

};