简体   繁体   English

将数据从服务传递到angularjs中的控制器

[英]Pass data from service to controller in angularjs

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); ) . 但是我总是在控制台中得到一个空对象( console.log(loginService.getInfo); )。 Let me know what I am doing wrong here. 让我知道我在这里做错了。

I am expecting session data in the this.getInfo . 我期望this.getInfo会话数据。

EDIT 编辑

If I am using .then then it is going in the if ie if (data.code!="200"){ here. 如果我使用的是if (data.code!="200"){ .then那么它将进入ifif (data.code!="200"){这里。

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: 并添加return给您的服务:

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;    
            }
        }); 
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM