如何将我的代码最小化为一个 api?AngularJS.



我有两个 API 在做同样的工作。 1(默认情况下,我正在获取当前日期的员工数据。 2(我正在传递参数以获取所选日期数据。 如何将代码最小化为一个 api?

app.controller("attCtrl", ['$scope', '$filter', '$http', function ($scope, $filter, $http) {
jQuery("body").on("focus", ".time-input", function () {
if (!jQuery(this).data('xdsoft_datetimepicker')) {
jQuery(this).datetimepicker({
onGenerate: function () {
if (!jQuery(this).hasClass('initial')) {
jQuery(this).addClass('initial').triggerHandler('open.xdsoft');
}
}
});
}
});
$scope.empattendance = [],
//I want to send default date while calling this api
$http.get('xyz/api/att/view/date')
.then(function (result) {
console.log(result);
$scope.empattendance = result.data.result;
$scope.empDetails = result.data.result1;
}, function (data, status) {
console.log(data);
});
$scope.getEmpAttendance = function () {
var employeeAttendance = {
startdate: jQuery('#start').val(),
enddate: jQuery('#end').val(),
employee: $scope.selectedItem
}
employeeAttendance.startdate = employeeAttendance.startdate.slice(0, -6);
employeeAttendance.enddate = employeeAttendance.enddate.slice(0, -6);
console.log(employeeAttendance);
$http.get('xyz/api/att/view/today', employeeAttendance)
.then(function (result) {
console.log(result);
$scope.empattendance = result.data.result;
});
}
}]);

您可以为 API 调用编写服务或在控制器中为单个函数编写服务,如下所示:

app.controller("attCtrl", ['$scope', '$filter', '$http', function($scope, $filter, $http) {
$scope.empattendance = [];
function getDetails(urlDate,employeeAttendance){
employeeAttendance = employeeAttendance || '';
return $http.get('xyz/api/att/view/'+urlDate, employeeAttendance);
}
//call API with default date
getDetails('date')
.then(function(result) {
console.log(result);
$scope.empattendance = result.data.result;
$scope.empDetails = result.data.result1;
}, function(data, status) {
console.log(data);
});
$scope.getEmpAttendance = function() {
var employeeAttendance = {
startdate: jQuery('#start').val(),
enddate: jQuery('#end').val(),
employee: $scope.selectedItem
}
employeeAttendance.startdate = employeeAttendance.startdate.slice(0, -6);
employeeAttendance.enddate = employeeAttendance.enddate.slice(0, -6);
// call API with date
getDetails('today',employeeAttendance)
.then(function(result) {
console.log(result);
$scope.empattendance = result.data.result;
});
}
}]);

希望这有帮助!

最新更新