I'm taking the data from different sharepoint pages lists. I'm calling these lists with a Factory.
My code is counting how many items with a "Completed" status each list has.
I need to take the values of each one into an array, but the result is always null
.
Here's my 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>
If I want to print each value separately, it shows the values! But if I try to put them inside the array, it shows the values as "null":
3
5
[null, null]
Why is this happening and how can I fix this? ..am I doing something wrong?
CODE UPDATE
Here is my code already working for those who'd like to see it. I changed the controller as Sergey Mell sugested, using $q, also I'm using AngularJS v1.7.5 (as georgeawg sugested):
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));
});
});