1

Well, I need to use a variable in different angular controllers or any function, which I can do, but in this particular case I'm getting the value of one of those variables from a service or a function, how you want to call it, this is the code

//global variable userdata
userdata = {};

ng.tcts.service('$user', function($http, $q, $window, $boots){
return{

    login: function(data){
        var deferred = $q.defer();

        $http({
            method:'POST',
            url:ng.api+'/log/in',
            data:{
                    data:data
                },
            headers:{'Content-type':'application/x-www-form-urlencoded'}        
        }).success(function(response, status, headers, config){
            if(response.success){
                console.log(response);
                //userdata assignation
                userdata = response.data;  
                deferred.resolve([response.respnum, response.success, response.report, response.data]);
            }
            else{
                deferred.resolve([response.respnum, response.success, response.report, response.data]);
            }
        }).error(function(response, status, headers, config){
            deferred.reject([response.respnum, response.success, response.report]);
        });
        return deferred.promise;        
    }

);

As you can see I'm asigining userdata the value of response.data inside the success function , when I use it in the function environment it works , the assignation works fine, but when I try to use it outside of it, the object is empty, I hope you can help me with this, thx

2
  • How are you calling it outside? Commented May 1, 2014 at 15:44
  • What do you mean, the variable or the service?, the service like thisdata = { username: $scope.username, password: $scope.password }; var promise = $user.login(data); Commented May 1, 2014 at 16:06

2 Answers 2

5

all you need to do is make a service that gets and set the user data and the data is kept inside the service. Then you make a method that returns that data and you can inject it into any controller in your app.

app.service('userData',function(){
var data;

this.get = function() {
    // do your ajax call to get your user data and in the response data = response;
}

this.data = function() {
    return data;
}
});

then in any controller:

function myCtrl($scope,userData) {
    // you can access it with this userData.data();

    // or set it to a $scope var

    $scope.userData = userData.data();
}

Making a global variable isn't how you use Angular you can create a service that you then inject into your controllers so multiple places can talk to that data or you can set it to a $rootScope var and then reference it in any controller. NEVER create a global variable and reference it in your controller though. This is how you end up with memory leaks in Angular.

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

5 Comments

But in this case I would have to make a call each time I need data of the user to the server, and that's what I want to avoid
no you wouldn't you get the data once assign it to data variable in the service and then you just use userData.data() to point to it. Trust me i do this in my app.
So you are saying that this will cut the cheese, or am I doing it wrong? plnkr.co/edit/FoKeHFu0y2QCOIk0jzKy?p=catalogue
@btm1 where do you call getdata()? I have to do it in every controller...otherwise data() is undefined...also I cannot assign like this "$scope.userData = userData.data()", because at the time of assignment data() is not returned yet from the server...
1

Not 100% clear on what your question is. If you are simply hoping to call this service from any controller and get the value of userdata, then just resolve your promise with the response.data.

So in your service:

deferred.resolve(response.data);

*or any other response items you need

And in the controller:

$user.login(payload).then(function(userData){
   console.log(userData);
});

If you want maintain this data after you have already made a request to the server, you could also just set somewhere in a variable (as @btm1 suggested) of a service, something like in the example below.

Example

10 Comments

What I need is to assign the response.data value to the userdata object
but I'm only calling it once, that's the why of the global variable, just cathing it once and use it all the session without making requests everytime the data is used
yes, then the second part (see bold) would be the way to go
I' don't get you could you explain me with an example, I made this plunkercan you tell me if that's what you mean plnkr.co/edit/eEa9Vef2UhR1WGgUV5ZN?p=info
Here is an example using movie info from a web service: plnkr.co/edit/3xML1Z4Uuxxp0yinRTPW?p=preview
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.