José Carlos
José Carlos

Reputation: 2922

AngularJS: How to sync an http call with a variable?

I'm trying to do a general function inside a controller which gives me the data from the backend and assign this data to a variable.

I have made this code, but it doesn't work correctly.

self.getData = function(url){
    var deferred = $q.defer();

    $http.get(url)
    .success(function(data){
        deferred.resolve(data);
        console.log("Total profiles: " + data.data.length);         
    })
    .error(function(error){
        //do something
    });

    return deferred.promise;
};

$scope.data = self.getData(ServiceURL.url[7]);
console.log("Total profiles inside function: " + $scope.data.length);

The call to the function works fine and give the total of profiles correctly, but when I try to assign this data to $scope.data it doesn't work fine because when I try to show the total of profiles with console.log("Total profiles: " + $cope.data.data.length) I've got the next exit:

Total profiles outside function: $scope.data: undefined

Furthermore, the execution is not synchronized, because first try to show the value of $scope.data and then the value from backend.

How can I synchronize this call and assign correctly the exit of the function to the $scope.data variable?

Is there any way to do what I want with a service? I'm trying to do it but $q variable always was undefined, and I don't know how to pass correctly. Do you have any example that works fine?

enter image description here

Upvotes: 0

Views: 115

Answers (2)

pjim
pjim

Reputation: 92

Can't you just set $scope.data within a function, then call the function like.

  function getProfiles(){
    $http.get(url).success(response){
        $scope.data = response;
     } 
  getProfiles();

Upvotes: 2

Rodmentou
Rodmentou

Reputation: 1640

ONE OPTION

is to assign your $scope.data within your return call from self.getData(). Like this:

$http.get(url)
    .success(function(data){
        deferred.resolve(data);
        $scope.data = self.getData(ServiceURL.url[7]); //Here is it.
        console.log("Total profiles: " + data.data.length);         
    });

Upvotes: 1

Related Questions