我正在尝试创建使用服务(工厂)和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 });
});
})
怎么了
感谢帮助!
它确实有效!我在做错的是在使用console.log进行调试时打印出错误的值以及我在UI中显示响应消息的方式。
总结一下,我想按POST / api / schedules / period //进行API调用//
该调用进行计算并发回我想在屏幕上显示最终用户的响应。
这是可以改进的工作代码,但对于基本用例来说却是一个相当不错的例子。如果您按照示例进行逻辑推理,则发送参数的语法相当简单。
调节器
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>
希望有人觉得这很有用。