Serhii
Serhii

Reputation: 7543

REST AngularJS @resource parametrized request

I have next 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'

Using angular i want use @resource to get information from server.

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

But using this declaration i do not have any API to request the page based on some data.

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

or to send update for eventHistory entity.

Upvotes: 1

Views: 86

Answers (2)

Serhii
Serhii

Reputation: 7543

the first answer seems good, but i think this way more understandable and simply for begginers:

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

to make page request in dynamic way the object should be build before request from ngTable current properties (use ngTable API).

Please pay your attention to eventHistoryFactory. It does not have parameter for pageRequest object, but it works -angular magic. By GET request in url you can see:

 ?page=2&size=25

Upvotes: 1

Muli Yulzary
Muli Yulzary

Reputation: 2569

Based on OP's comment:

Say you want to update a single entity:

.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();
});

Upvotes: 2

Related Questions