Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

update a service variable within an $http callback

I'm using a service to make user data available to various controllers in my Angular app. I'm stuck trying to figure out how to use the $http service to update a variable local to the service (in my case "this.users"). I've tried with and without promises. The server is responding correctly.

I've read several excellent articles for how to use $http within a service to update the scope of a controller. The best being this one: http://sravi-kiran.blogspot.com/2013/03/MovingAjaxCallsToACustomServiceInAngularJS.html. That does not help me though because it negates the benefits of using a service. Mainly, modifying the scope in one controller does not modify throughout the rest of the app.

Here is what I have thus far.

app.service('UserService', ['$http', function($http) {
    this.users = [];

    this.load = function() {
        var promise = $http.get('users.json')
            .success(function(data){
                // this.users is undefined here
                console.log(this.users);
            }
    };

    promise.then(function() {
        // this.users is undefined here
        console.log('this.users');
    });
}]);

Any help is greatly appreciated. Thank you.

like image 975
guyja Avatar asked Apr 30 '14 20:04

guyja


2 Answers

Try using

var users = [];

rather than

this.users = [];

and see what

console.log(users);

outputs in each of those cases.

like image 79
sfletche Avatar answered Nov 15 '22 05:11

sfletche


Your service is oddly defined, but if you have a return in it you can access it from any controller:

app.service('UserService', ['$http', function($http) {
    var users = [];
    this.load = function() {
        var promise = $http.get('users.json')
            .success(function(data){
                // this.users is undefined here
                console.log(users);
                users = data.data;
            }
    };
    return {
        getUsers: function(){
            return users;
        }
    }  
}]);

so in your controller, you can use:

var myUsers = UserService.getUsers();

UPDATE to use a service correctly here, your service should return a promise and the promise should be accessed in the controller: Here's an example from another answer I gave

// your service should return a promise
app.service('PickerService', [$http', function($http) {
    return {
        getFiles: function(){ 
            return $http.get('files.json'); // this returns a promise, the promise is not executed here
        }
    }
}]);

then in your controller do this:

PickerService.getFiles().then(function(returnValues){ // the promise is executed here as the return values are here
    $scope.myDirectiveData = returnValues.data;
});
like image 41
SoluableNonagon Avatar answered Nov 15 '22 05:11

SoluableNonagon