将多个参数从控制器传递到工厂服务进行 REST 调用并返回(可选)数据

Posted

技术标签:

【中文标题】将多个参数从控制器传递到工厂服务进行 REST 调用并返回(可选)数据【英文标题】:Passing multiple arguments from controller to factory service making REST calls and returning (optional) data 【发布时间】:2018-06-06 00:16:50 【问题描述】:

我正在尝试创建使用服务(工厂)和 ngResource 向 RESTful 服务发送请求的代码,该服务根据业务逻辑执行和操作并发送可选结果。

我知道有一个问题与 Passing multiple parameters from controller to factory in angularjs 上的类似内容有关。我在让它为我工作时遇到问题,而且也缺乏解释。

我写这篇文章是为了了解它是如何工作的、最佳实践,因此有一个存储库对将来像我这样的新手有好处。没有不尊重上面提供的解决方案的作者,但它可能假设我还没有达到一定程度的聪明;-)

这里是:

我的控制器

swof.controller('scheduleController', ['$scope', '$log', '$http', '$filter','moment', 'scheduleServicePeriod', function($scope, $log, $http, $filter, moment, scheduleServicePeriod) 

  $scope.name = 'scheduleController::set default values and provide function to generate new schedule';
  $log.info('Controller: '+ $scope.name);
  $scope.years = ["2017", "2018", "2019","2020","2021","2022"];
  $scope.selectedYear = "2017";
  $scope.selectedPeriod = Math.ceil(moment().format('w')) | 1 ;
  $scope.genSchedule = function()
  
    // when button is pressed function 'genSchedule' is called that either has default value for selectedYear and selectedPeriod or one user has selected. This bit works
    scheduleServicePeriod.post( s_year: $scope.selectedYear, s_period: $scope.selectedPeriod ).$promise.then(function(data)
      $scope.schedulegen = data;
        $scope.genScheduleResponse=moment().format('h:mm:ss a') + " " + data.message;
    , function(data) 
      $log.error();('Error: ' + data);
    );

]);

我的工厂服务

swof.factory('scheduleServicePeriod', function($resource)

  var data = $resource('/api/schedules/period/:s_year/:s_period',s_year: "@s_year",s_period: "@s_period" ,
  
    'post':
    
      method: 'POST',
      params: ,
      isArray:true
    
  );
  return data;
);

我的 RESTful Web 服务

  router.route('/schedules/period/:schedule_year/:schedule_period')

    .post(function(req,res)
    
      // create record
      var query =  getEngineerIDs();
      var jsonMessage = "Success: Generated schedule for year = " + req.params.schedule_year + " and period starting week number =   " + req.params.schedule_period ;

      console.log(parseInt(req.params.schedule_period%2),parseInt(req.params.schedule_period));

      query.exec(function(err,records)
      
        if(err) return console.log(err);
        var results = SwfFn.populateCalendar(SwfFn.assignEngineers(records),+
                      req.params.schedule_year,req.params.schedule_period);
        if ( results.length == 0  ) 
          jsonMessage = "Failed: Start year/week in past";
        
        console.log(jsonMessage);
        for (var count in results)
        
          Schedule.findOneAndUpdate (
             ymd: results[count].ymd, shift: results[count].shift ,
            results[count],
            upsert: true, new: true, runValidators: true,
            function (err,res)  if (err) res.send(err); 
          );
        
        res.json(message: jsonMessage );
      );

    )

会发生什么

    值(默认或其他)到达函数 genSchedule。 到达 RESTful 服务的值为 'undefined' 'undefined' 问题出在工厂服务上。 有一个类似的解决方案,我不必工作(上图) 我知道您应该只将一个 JSON 从控制器发送到服务,但我不确定如何在工厂端处理它。 我(还)不能让检索部分工作,但现在可以等待。

感谢您的帮助!

【问题讨论】:

在docs.angularjs.org/api/ngResource/service/$resource 找到了一些东西。仍在阅读它,但认为它以稍微不同的方式(代码的结构化方式)解决了我想要的问题。 【参考方案1】:

它确实有效!我做错了什么是在使用 console.log 进行调试时打印出错误的值,以及我在 UI 中显示响应消息的方式。

总而言之,我想按照以下方式进行 API 调用 POST /api/schedules/期间//

调用会进行计算并发回我想在屏幕上显示最终用户的响应。

这里的工作代码仍然可以改进,但对于基本用例来说是一个相当不错的例子。如果您按照示例得出合乎逻辑的结论,则发送参数的语法相当简单。

控制器

swof.controller('scheduleController', ['$scope', '$log', '$http', '$filter','moment', 'scheduleServicePeriod', function($scope, $log, $http, $filter, moment, scheduleServicePeriod) 

  $scope.name = 'scheduleController::set default values and provide function to generate new schedule';
  $log.info('Controller: '+ $scope.name);
  $scope.years = ["2017", "2018", "2019","2020","2021","2022"];
  $scope.selectedYear = "2017";
  $scope.selectedPeriod = Math.ceil(moment().format('w')) | 1 ;

  $scope.genSchedule = function()
  
    scheduleServicePeriod.post( s_year: $scope.selectedYear, s_period: $scope.selectedPeriod ).$promise.then(function(data)
      $scope.schedulegen = data;
      $scope.genScheduleResponse=moment().format('h:mm:ss a') + " " + data.message;
    , function(data) 
      $log.error();('Error: ' + data);
    );

]);

工厂服务

swof.factory('scheduleServicePeriod', function($resource)

  var data = $resource('/api/schedules/period/:s_year/:s_period',s_year: "@s_year",s_period: "@s_period" ,
  
    'post':
    
      method: 'POST'
    
  );
  return data;
);

RESTful 调用

  router.route('/schedules/period/:schedule_year/:schedule_period')

    .post(function(req,res)
    
      // create record
      var query =  getEngineerIDs();
      var jsonMessage = "Success: Generated schedule for year/period [" + req.params.schedule_year + "/" + req.params.schedule_period +"]" ;

      query.exec(function(err,records)
      
        if(err) return console.log(err);
        var results = SwfFn.populateCalendar(SwfFn.assignEngineers(records),+
                      req.params.schedule_year,req.params.schedule_period);
        if ( results.length == 0  ) 
          jsonMessage = "Failed: Start year/week in past";
        
        for (var count in results)
        
          // Write record to Mongo using upsert; if records for future date already
          // here then overwrite them otherwise insert. This is ok since the period
          // is in the future
          Schedule.findOneAndUpdate (
             ymd: results[count].ymd, shift: results[count].shift ,
            results[count],
            upsert: true, new: true, runValidators: true,
            function (err,res)  if (err) res.send(err); 
          );
        
        res.json(message: jsonMessage );
        console.log(jsonMessage);
      );

网页

<div>
  <h3>Generate</h3>
<h4>Generate schedule for future periods</h4>
<p>Select year and week start period to generate a schedule for future support slots. Previously generated values will be lost. You cannot generate  a scheule for periods in the past or the current period we are in.</p>
<form name="scheduleGenerate">
   <select ng-model="selectedYear" ng-options="x for x in years"></select>
   Start Week (1-51 [odd numbers]):
   <input ng-model="selectedPeriod" type="number" name="genperiod" placeholder="1" min="1" max="51" step="2" onkeydown="return false">
   <input type="button" class="click" id="click" value="Generate" ng-click="genSchedule()">
   <label class="control-label">   genScheduleResponse </label>
 </form>
</div>

希望有人觉得这很有用。

【讨论】:

我的代码可以在github.com/gmanroney/supportscheduler找到。除了 html5、css3 和一些 web 框架之外,我正在使用这个“产品”理念作为学习 nodejs、angularjs 的一种方式。随意看看。我尝试发表评论,使其对任何想要访问它的人都有意义和有用......

以上是关于将多个参数从控制器传递到工厂服务进行 REST 调用并返回(可选)数据的主要内容,如果未能解决你的问题,请参考以下文章

如何将多个参数从 ajax 调用传递到 MVC 控制器

将多个参数从 ajax post 传递到 asp.net mvc 控制器

将上下文从 Web 请求的控制器传递到数据库层

如何使用 REST 将数据从 AngularJS 发布到 Struts 2

将日期时间参数从管道传递到数据流源存储过程 Azure 数据工厂

将嵌套参数传递到 Azure 数据工厂