7

I am new to angularjs, and I am trying to return the data from a function to another function, and store it in a variable.

$scope.myNameValidate = function(name){
    $scope.friendsList = $scope.getAllFriends(name);
    console.log("data", $scope.friendsList);
}

$scope.getAllFriends = function(name){
    friendService.getAllfriends(name) 
    .then(function(data){
        //success
        console.log(data);
    }, function(err){
        //error
    })
}

I want to store all the objects in a variable but I get undefined as result.

output in console

data undefined

[Object, Object, Object, Object, Object, Object]

4 Answers 4

9

You need to know the Angular promise.

This issue related to Asynchronous operation.

You can fix it with proper thenable chaining. You can do it in this way.

$scope.myNameValidate = function(name) {
    $scope.getAllFriends(name)
        .then(function(data) {
            $scope.friendsList = data;
            console.log(data);
        }, function(err) {
            //error
        });

}

$scope.getAllFriends = function(name) {
    return friendService.getAllfriends(name)

}
Sign up to request clarification or add additional context in comments.

Comments

2

Why its' undefined?

Your function $scope.getAllFriends() is not returning anything witch can set data to $scope.friendsList.

function myFunc(){
 var i = 5;
}
var myVar = myFunc();

myVar will not have value 5.

function myFunc(){
 var i = 5;
return i;
}
var myVar = myFunc();

In angular even if it's asynchronous data when you set to $scope as soon data has arrived angular will update your view and scope.

Comments

1

You cannot use async callbacks this way. In your particular case you should set $scope.friendsList inside the success callback.

$scope.myNameValidate = function(name) {
    $scope.getAllFriends(name);
}

$scope.getAllFriends = function(name) {
    friendService.getAllfriends(name) 
    .then(function(data) {
        $scope.friendsList = data;
        console.log("data", $scope.friendsList);
    }, function(err){
        //error
    })
}

Comments

1
$scope.myNameValidate = function(name){
$scope.friendsList = $scope.getAllFriends(name)
   .then(function(data){
    //here is your data
   })
  .catch(error){
   //Error
   }
console.log("data", $scope.friendsList);
}

$scope.getAllFriends = function(name){
  var promise = friendService.getAllfriends(name) 
   .then(function(data){
     return data;
  }, function(err){
    //error
 })
 return promise;
 }

This is asynchronus call thats why you got undefined

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.