Hello, I'm new to AngularJS and currently facing an issue with accessing a returned value from a Factory Service Function called myFactoryService, so that I can utilize it in my Controller named RequestsController
.
Let's take a look at the code snippet. The first part involves the HolidaysService
, which is responsible for fetching an array of Dates from the server side (implemented in C#) and returning it upon successful operation:
app.factory('HolidaysService', function ($http) {
var fac = {};
fac.getHolidays = function (d) {
return $http({
method: 'GET',
url: '/RequestAng/getHolidays'
}).then(function successCallback(response) {
var dates = []; // initializing an empty array for Holidays
var i = 0;
var counter = 0;
for (var i in response.data) {
dates[i] = new Date((parseInt(response.data[i].substr(6)))); // parsing the JSON Values obtained
i++;
}
return dates;
}, function errorCallback(response) {
console.log(response);
});
}
return fac;
});
Next, we have another Factory utilizing HolidaysService
, defined earlier, to retrieve the array of dates and perform certain computations:
app.factory('myFactoryService', function (HolidaysService ) {
var service = {};
var counter = 0;
service.Calc = function (d1, d2) {
HolidaysService.getHolidays().then(
function (dates) {
var i = 0;
for (i in dates) {
if (dates[i] >= d1 && dates[i] <= d2) {
if (dates[i].getDay() !== 6 && dates[i].getDay() !== 7) {
counter++; // The needed value for later use in the controller
}
}
i++;
}
return counter;
}
);
}
return service;
});
My aim now is to access the returned value from myFactoryService
within the RequestsController
like so:
(function () {
var app = angular.module('RM', ['ui.date']);
app.controller('RequestsController', function ($scope, $http, myFactoryService) {
$scope.counter=0;
$scope.Request = {
Remaining: '',
DateRequest: new Date(),
DateBeg: '',
DateEnd: ''
};
/* This code segment updates the 'Remaining' Input TextField when Dates change */
var names = ['Request.DateBeg', 'Request.DateEnd'];
$scope.$watchGroup(names, function (newValues, oldValues, $scope) {
var businessDays = $scope.CalcBusinessDays(); // Calculates business days between two dates
if (businessDays !== -1) {
var x = 1;
x = myFactoryService.Calc($scope.Request.DateBeg, $scope.Request.DateEnd);
console.log("printing x: " + x);
}
});
});
Whenever I attempt to access the value returned from myFactoryService
, it always results in undefined
. Any suggestions or solutions would be greatly appreciated. Thank you in advance for your help. (Apologies for the lengthy post)