javascript - 在AngularJS中将数据从服务传递到 Controller

标签 javascript angularjs angularjs-service

以下是我的服务代码 -

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

我的 Controller 代码 -

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

但是我总是在控制台中得到一个空对象( console.log(loginService.getInfo); )。让我知道我在这里做错了什么。

我期待 this.getInfo 中的 session 数据。

编辑

如果我使用.then,那么它将进入if,即if (data.code!="200"){在这里。

最佳答案

你必须等待 promise 。

在你的 Controller 中使用它:

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

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

关于javascript - 在AngularJS中将数据从服务传递到 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23991652/

相关文章:

javascript - 延迟服务和 Controller

javascript - 对象数组的深度减少(可能是采摘?)

javascript - 这个 protobuf 解码有什么问题?

javascript - Jquery:- 计算每个 tr 中 td 的数量

javascript - 需要来自 Angular js 的跨源请求示例

javascript - ng-show 在隐藏之前是可见的

javascript - AngularJS 使用 $interval

php - javascript字符串替换php上的等价物?

javascript - AngularJS UI 路由器嵌套状态不工作

javascript - 使用 Angularjs 在 DeviceReady 后注入(inject)服务或执行服务