I am new to AngularJS and still relativly new to JS at all. I tried to implement an angularjs project with login informations, etc.
Now I call by http request an API and get an answer with the user and the users objects. When I open the site, the console.logs show an result of 0 users and user=undefined. But when I open the objects in the console window, they are filled. So that means, the results are not there at the opening of the page, but are loaded async. So far, so clear.
But I thought the bindings in AngularJS were bindings that update themselves as soon as the value changes. I looked around for a while and found as answer that I should use a factory, but I don't know how. Can someone point me in the right direction please?
HTML
<h1>Hi {{vm.user.firstname}}!</h1>
<p>You're logged in! Test{{testService.test}}!</p>
<h3>All registered users:</h3>
<ul>
<li ng-repeat="user in vm.allUsers">
{{user.username}} ({{user.firstname}} {{user.lastname}})
- <a ng-click="vm.deleteUser(user.id)">Delete</a>
</li>
</ul>
controller.js
angular
.module('app')
.controller('HomeController', HomeController);
HomeController.$inject = ['UserService', '$rootScope'];
function HomeController(UserService, $rootScope) {
var vm = this;
vm.user = null;
vm.allUsers = [];
vm.deleteUser = deleteUser;
initController();
function initController() {
loadCurrentUser();
loadAllUsers();
log(vm);
}
function loadCurrentUser() {
UserService.GetByUsername($rootScope.globals.currentUser.username).then(resolve => {
vm.user = resolve.message;
});
}
function loadAllUsers() {
UserService.GetAll().then(resolve => {
vm.allUsers = resolve.message;
});
}
function deleteUser(id) {
UserService.Delete(id).then(() => {
loadAllUsers();
});
}
}
EDIT: I found the solution. It is not the asyncronicity that makes a problem here. It is simply the reading of the returned data.
vm.allUsers = resolve.message.recodsets;
That gives all Recordsets for going through with ng-repeat and to get the one logged in user it was:
vm.user = resolve.message.recodset[0];
That is a little bit embarrassing but this way it works.