如何将多个对象从工厂发送到REST服务

时间:2015-11-19 14:20:13

标签: angularjs rest factory

我是AngularJS的新手,在将多个对象从我的工厂发送到我的REST服务时遇到了麻烦。

我已经成功完成了一个用过滤器对象

调用RESTful服务的函数
myFactory.getActivities =  function(filter) {
    return $http.post('ws/activities', filter);
};

但现在我需要修改REST服务以再接收一个对象'分页'。

我试过了:

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

但它不起作用(因为$ scope未在工厂中定义)。

我的问题是,如何将这些值发送到我的REST服务?

2 个答案:

答案 0 :(得分:1)

只有控制器和指令具有$ scope,您必须将其作为参数传递:

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

或者,更清楚,只传递你想要的值:

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

或更短:

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

答案 1 :(得分:0)

设计工厂或服务的简洁方法:

Factory.js

my-app-user

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