Assign function return to a variable using Angularjs $Promise

Asked

Viewed 2,203 times

1

I have an angle.Factory that returns data from json. Within a controller I invoke the same to take the data, the point is that by invoking the same within the controller the object exists only if you use a console.log, If you set a variable, it is empty. Could someone help me?

//Factory
app.factory('dataLoad', function($http, $q) {
     return {
         getContent: function() {
            var deferred = $q.defer();

            $http.get('data-json.php')
            .success(function(data) {
                deferred.resolve(data);
            })
            .error(function() {
                deferred.reject();
            });

            return deferred.promise;
        }
    }
});

Controller:

$scope.node = [];

dataLoad.getContent().then(
    function(data) {
        //Objeto é impresso normalmente
        console.log(data);

        //nulo
        $scope.node = data;
    }
);

console.log($scope.node);

1 answer

2

What happens is this, your getContent is an asynchronous function, so when you do the console.log($Scope.Node) the Promise was not yet resolved.

When any attribution is made within a Promise it will never be available immediately but only when the Promise is solved.

Try to use a $watch to test and see what happens.

EX:

$scope.node = [];

dataLoad.getContent().then(
  function(data) {
      //Objeto é impresso normalmente
      console.log(data);

      //nulo
      $scope.node = data;
  }
);
$scope.$watch('node', function(new_value, old_value){
  console.log($scope.node, new_value, old_value);
})
  • I used the $watch and the data is now present. In case I always have to use watch to get the data?

  • If you have print in the view {{Node}} it will work without the $watch because the angular makes a bind of this property, the issue is that the console log. is executed before Promise is resolved. What you really need to do?

  • Daniel, I need to assign the return to a variable, because I will call Factory N times and with the return I will call another method to display the data.

  • I believe that the correct then would be to call your method within the .then instead of assigning to a variable to then call the method.

  • Thanks Daniel. Subject solved with the code you sent.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.