Reputation: 1229
I'm struggling with using the value that I got from a 'get' in my controller.
This is my code in my controller
vm.user;
function onInit(){
loadUser(vm.queryParams.id[0]);
console.log(vm.user);
}
function loadUser(UserId) {
var defer = $q.defer();
User.get({ id: userId }).$promise.then(function (user) {
vm.user = user;
defer.resolve();
});
return defer.promise;
};
When I print the vm.user
in the onInit()
it is undefined. While when I look on the view where vm.user is called it just shows me the correct values of the user. So it's not known after the loadUser()
in the controller but it is in my view.
I would like to first 'get' the user and then use it for further logic in the onInit()
. How to retrieve the user properly so I can further use it and call its values in the onInit()
?
Upvotes: 2
Views: 41
Reputation: 276
Immediately invoke your init function at the beginning of your controller and convert your loadUser function to a service since its a get action. Your service will return the user which you can then set.
(Declare at top of controller):
init();
function init(){
loadUserService.loadUser(UserId)
.then(function (user) {
vm.user = user;
defer.resolve();
})
}
Upvotes: 0
Reputation: 6630
You have to wait till the execution of loadUser()
is finished so as the get the value of user.You can use the promise returned like this and do any calcualtions on it.
vm.user;
function onInit(){
var promise=loadUser(vm.queryParams.id[0]);
promise.then(function(response){
console.log(response);
});
}
function loadUser(UserId) {
var defer = $q.defer();
User.get({ id: userId }).$promise.then(function (user) {
vm.user = user;
defer.resolve(vm.user);
});
return defer.promise;
};
Upvotes: 1