I am extracting data from various SharePoint pages lists by utilizing a Factory.
Within my code, I am determining the number of items with a "Completed" status in each list.
I am attempting to store these values in an array, but it consistently returns null
.
Take a look at this example:
<script>
var myApp = angular.module("myApp", []);
myApp.factory("myFactory", ["$http", function($http) {
return {
siteOne: function() {
return $http({
method: "GET",
url: "siteURL/_api/web/lists/getByTitle('List 1')/items",
headers: {"Accept": "application/json; odata=verbose"}
});
},
siteTwo: function() {
return $http({
method: "GET",
url: "siteURL/_api/web/lists/getByTitle('List 2')/items",
headers: {"Accept": "application/json; odata=verbose"}
});
}
}
}]);
myApp.controller("myController", function($scope, $http, myFactory) {
myFactory.siteOne().success(function(data, status, headers, config) {
$scope.projects = data.d.results;
var items = $scope.projects,
totalItems = 0;
for (var i=0;i<items.length;i++) {
var currentItem = items[i];
if(currentItem.Status!="Completed") {
totalItems++;
}
};
$scope.oneItems = totalItems;
});
myFactory.siteTwo().success(function(data, status, headers, config) {
$scope.projects = data.d.results;
var items = $scope.projects,
totalItems = 0;
for (var i=0;i<items.length;i++) {
var currentItem = items[i];
if(currentItem.Status!="Completed") {
totalItems++;
}
};
$scope.twoItems = totalItems;
});
$scope.data = [
$scope.oneItems, $scope.twoItems
];
console.log(JSON.stringify($scope.oneItems));
console.log(JSON.stringify($scope.twoItems));
console.log(JSON.stringify($scope.data));
});
</script>
When attempting to display the values individually, they are correct! However, when trying to insert them into an array, they show as "null":
3
5
[null, null]
Why is this occurring and what steps can I take to resolve it? Could there be something incorrect in my approach?
CODE UPDATE
Below is the updated working code based on suggestions from Sergey Mell and using $q, also leveraging AngularJS v1.7.5 (as recommended by georgeawg):
myApp.controller("myController", function($scope, $http, myFactory, $q) {
$q.all([
myFactory.siteOne().then(response => {
var items = response.data.d.results,
totalItems = 0;
for (var i=0;i<items.length;i++) {
var currentItem = items[i];
if(currentItem.Status!="Completed") {
totalItems++;
}
};
$scope.oneItems = totalItems;
}),
myFactory.siteTwo().then(response => {
var items = response.data.d.results,
totalItems = 0;
for (var i=0;i<items.length;i++) {
var currentItem = items[i];
if(currentItem.Status!="Completed") {
totalItems++;
}
};
$scope.twoItems = totalItems;
})
]).then(function() {
$scope.data = [
$scope.oneItems, $scope.twoItems
];
console.log(JSON.stringify($scope.data));
});
});