jnoo
jnoo

Reputation: 3

How to send multiple objects from factory to REST service

I'm new to AngularJS and in trouble sending multiple objects from my Factory to my REST service.

I have successfully done a function which calls the RESTful service with a filter object,

myFactory.getActivities =  function(filter) {
    return $http.post('ws/activities', filter);
};

but now I need to modify the REST service to receive one more object 'pagination'.

I tried this:

myFactory.getActivities = function (filter, pagination) {
    return $http.post('ws/getActivities', {
        activityId : $scope.activityId,
        otherParameter : $scope.otherParameter
    },{
        numPage : $scope.numPage,
        numRegisters : $scope.numRegisters
  });
};

but it doesn't work (because $scope isn't defined in the factory).

My question is, what should i do to send those values to my REST service?

Upvotes: 0

Views: 788

Answers (2)

Shaohao
Shaohao

Reputation: 3531

A clean way to design your factory or service:

Factory.js

angular.module('myApp')
  .factory('myFactory', function($http, $q) {
    return ({
      getActivities: getActivities
    });

   // Restful POST call with 4 parameters
   // @Param: activityId, otherParameter, numPage, numRegisters
   function getActivities (activityId, otherParameter, numPage, numRegisters) {
     var request = $http({
       method: 'post',
       url: 'ws/activities',
       params: {
         activityId: activityId,
         otherParameter: otherParameter,
         numPage: numPage,
         numRegisters: numRegisters
       }
     });
     return( request.then ( handleSuccess, handleError) );
   }

   // When POST success, it returns stauts code
   // should be status: 200
   function handleSuccess( response ) {
     return (response.status);
   }
   // When fail to POST data, if return the failure message
   function handleError( response ) {
     return($q.reject(response.data.message));
   }
  });

Controller.js

angular.module('myApp')
  .controller('MainController', function($scope, myFactory) {
    [...]
    myFactory.getActivities($scope.activityId, $scope.otherParameter, $scope.numPage, 
                            $scope.numRegisters).then(
      function(status) {
        // you get the status from backend
        // do whatever you want here
      },
      function(error) {
       // fail to POST to backend
       // implement your logic how to handle failure
      }
    );   
});

Upvotes: 0

Dani Barca Casafont
Dani Barca Casafont

Reputation: 273

Only controllers and directives have an $scope, you'll have to pass it as parameter:

myFactory.getActivities = function (filter, pagination, scope){...

Or, even clearer, pass only the values you want:

myFactory.getActivities = function (filter, pagination, otherParameter, numPage,numRegisters){...

or shorter:

myFactory.getActivities = function (filter, pagination, objectWithData){...

Upvotes: 1

Related Questions