2016-06-16 49 views
1

我很困惑如何使用$ 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 

    }; 

我如何成功地更新這一資源?

回答

0

想通了!

當我定義資源時,我將PUT操作定義爲一種名爲'update'的自定義方法。

我打電話給那個資源,並通過ID查找一個特定的對象。 使用承諾,如果找到對象,我可以使用'更新方法'更新資源,否則會拋出錯誤。

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

};