0

Following is my Service code -

myApp.service('loginServiceChk', function(){
    this.getInfo = {};
    this.chkLogin = function($http,$location,$window){
        $http.get('/users/chklogin')
            .success(function (data, status, headers, config) {             
                if (data.code!="200"){
                    this.getInfo = {};
                    $window.location.href='/#/users/login';
                }else{
                    this.getInfo = data.usersession;    
                }
            }); 
    };
});

My controller code -

myApp.controller('userDash',function($scope,$http,$location,loginServiceChk,$window){
    loginServiceChk.chkLogin($http,$location,$window);
    console.log(loginService.getInfo);
    $scope.userLogout = function() {        
        $http.get('/users/logout').success(function (data, status, headers, config) {
            if (data.logout=="200"){
                merInfo = {} ;
                $window.location.href='/#/userss/login';
            }   
        })
    };
});

However I am always getting an empty object in the console ( console.log(loginService.getInfo); ) . Let me know what I am doing wrong here.

I am expecting session data in the this.getInfo.

EDIT

If I am using .then then it is going in the if ie if (data.code!="200"){ here.

3
  • 1
    chkLogin is asynchronous. When you log loginService.getInfo, it hasn't completed yet, so its blank. You should return a promise object from your chkLogin function. Commented Jun 2, 2014 at 9:50
  • 1
    Since chkLogin is asynchronous call, getInfo is not yet populated by the time you are trying to access it. Commented Jun 2, 2014 at 9:53
  • @dfsq I am looking this docs.angularjs.org/api/ng/service/$q but can you please help me to fit this in my scenario as I haven't used promise mefore Commented Jun 2, 2014 at 9:56

1 Answer 1

1

You have to wait for the promise.

Use this in your controller:

loginServiceChk.chkLogin($http,$location,$window).then(function() {
    console.log(loginService.getInfo);
});

And add return to your service:

this.chkLogin = function($http,$location,$window){
    return $http.get('/users/chklogin')
        .then(function (data, status, headers, config) {             
            if (data.code!="200"){
                this.getInfo = {};
                $window.location.href='/#/users/login';
            }else{
                this.getInfo = data.usersession;    
            }
        }); 
};
Sign up to request clarification or add additional context in comments.

3 Comments

should call then() - its more verbose, but it allows for chaining promises.
Absolutely, I missed that one
@PatrickReck This code making my page refresh everytime ..somekind of recursion

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.