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

user3384672
  • 73
  • 1
  • 3
  • 11

2 Answers2

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.

btm1
  • 3,866
  • 2
  • 23
  • 26
  • 1
    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 – user3384672 May 01 '14 at 16:34
  • 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. – btm1 May 01 '14 at 21:52
  • So you are saying that this will cut the cheese, or am I doing it wrong? http://plnkr.co/edit/FoKeHFu0y2QCOIk0jzKy?p=catalogue – user3384672 May 01 '14 at 22:06
  • almost this is more like it http://plnkr.co/edit/SaewaPKIGV37KHE83Fiu?p=catalogue – btm1 May 03 '14 at 01:26
  • @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... – Michal B. Feb 28 '18 at 08:42
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

Dan Dascalescu
  • 143,271
  • 52
  • 317
  • 404
  • What I need is to assign the response.data value to the userdata object – user3384672 May 01 '14 at 15:57
  • 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 – user3384672 May 01 '14 at 16:04
  • yes, then the second part (see bold) would be the way to go – Dave Gavigan May 01 '14 at 18:24
  • 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 http://plnkr.co/edit/eEa9Vef2UhR1WGgUV5ZN?p=info – user3384672 May 01 '14 at 19:23
  • Here is an example using movie info from a web service: http://plnkr.co/edit/3xML1Z4Uuxxp0yinRTPW?p=preview – Dave Gavigan May 01 '14 at 22:07
  • Do you think this structure can do it? http://plnkr.co/edit/FoKeHFu0y2QCOIk0jzKy?p=catalogue – user3384672 May 01 '14 at 22:28
  • I would say no. Theres some things fundamentally wrong with what your doing in your newest plnkr. (like setting `response.data = data` when your calling your returned payload `response`. I would suggest trying to understand my example more thoroughly and fit it to your request. – Dave Gavigan May 02 '14 at 04:05
  • could you mark this correct if this answer helped or answer your question? – Dave Gavigan May 02 '14 at 21:14
  • This answer isn't correct. Yes you're saving the movie to the service but you should never save anything to a service as a method in the service this.movie ... you should just create a variable in the service movie and set movie equal to the response and then create another method to return the data. This way the data in private to the service and is not automatically included every time the service is injected into a controller. – btm1 May 03 '14 at 01:31
  • good point. credit deserved where credit is due – Dave Gavigan Jun 20 '14 at 17:59