I am trying to make a console.log()
of a array
that fills when I make the request http
but prints empty, it is possible to make it execute the entire function of the first http
$scope.users();
and then output the result to the console.
PS : console.log
I can do it within the request http
but it is not what I want, is there any other way, promises or something similar?
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http, $filter) {
$scope.users = function() {
$scope.arrItem = [];
$http.get('https://jsonplaceholder.typicode.com/todos').then(function(res) {
$scope.users = res.data;
$filter('filter')($scope.users, function(value, index, array){
if (value.userId == 1) {
$scope.arrItem.push(value);
};
} , true);
});
}
$scope.test = function() {
$scope.users();
console.log($scope.arrItem);
}
$scope.test();
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<div ng-repeat="user in arrItem">
{{ user }}
</div>
</body>
</html>
For the problem I had, I had to use the $q
angularJs
call service to handle the promises and it was just what I was looking for, there are several ways to make promises... In the function we make use of the service as you can see below:$scope.users();
$q
I have actually programmed very little with Angular JS, but the solution that I propose is the following.
As you have said, do it with promises and not advance until you have the data.
Here the example.
Here in case you want to try it -> Link
First of all, I recommend separating the controller from the services, so that you have a better organization of the code and you can reuse it. In this case you can place the controller something like this
Now create the services.js file, or whatever you want to call the service
You can also do it in the same file. It would be something like this
Remember that you must add the new file in the index.
I will gladly answer any questions. I hope I've helped.