簡體   English   中英

將數據從服務傳遞到angularjs中的控制器

[英]Pass data from service to controller in angularjs

以下是我的服務代碼-

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

我的控制器代碼-

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會話數據。

編輯

如果我使用的是if (data.code!="200"){ .then那么它將進入ifif (data.code!="200"){這里。

您必須等待諾言。

在控制器中使用此命令:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM