REST AngularJS @resource参数化请求

时间:2016-06-14 15:59:45

标签: angularjs rest parameters resources request

我有下一个WEB API:

GET     List<EventHistory> '/service/eventhistories'
GET     EventHistory       '/service/eventhistories/{id}'
DELETE  EventHistory       '/service/eventhistories/{id}'
PUT     EventHistory       '/service/eventhistories'
POST    EventHistory       '/service/eventhistories'

使用angular我想使用 @resource 从服务器获取信息。

angularApp.factory('eventHistoryFactory', function ($resource) {
   return $resource('/inner/service/eventhistories/:id',{id:'@id'});
});

但是使用这个声明我没有任何API来根据某些数据请求页面。

var pageRequest = {
    size: size,
    page: page
};

或发送 eventHistory 实体的更新。

2 个答案:

答案 0 :(得分:2)

基于OP的评论:

假设您要更新单个实体:

.controller('someCtrl', function($stateParams, eventHistoryFactory){
 //For the sake of the demonstration - id comes from the state's params.
 var eventHistory = eventHistoryFactory.get({id: $stateParams.id});

 eventHistory.$promise.then(function(){
  //Modify the entity when HTTP GET is complete
  eventHistory.address = 'New York';

  //Post the entity
  eventHistory.$save();

  //If you wish to use PUT instead of POST you should declare that
  //in the class methods of $resource
 });



 //Another example using query
 var entries = eventHistoryFactory.query({
  page: 0,
  size: 20,
  before: Date.now()
 });

 //This is translated into GET /inner/service/eventhistories?page=0&size=20&before=111111111111
 //and should be interpreted correctly by your backend.

 entries.$promise.then(function(){
  //entries now contain 20 first event history with date earlier than now.
  var specificEntry = entries[0];

  //Same deal - modify the entity when HTTP GET is complete
  specificEntry.address = 'New York';

  //Post the entity
  specificEntry.$save();
});

答案 1 :(得分:1)

第一个答案似乎很好,但我认为这种方式更容易理解,只是对于初学者来说:

    eventHistoryFactory.get(pageRequest, function (returnData) {
      console.trace('request processed successfully: ' + returnData);
      params.total(returnData.totalElements);
      $defer.resolve(returnData.content);
    }, function (error) {
      console.log('request processed with error: ' + error);
    })

以动态方式发出页面请求,应该在ngTable当前属性请求之前构建对象(使用ngTable API)。

请注意eventHistoryFactory。它没有pageRequest对象的参数,但它有效 - 魔术。通过URL中的GET请求,您可以看到:

 ?page=2&size=25