Javascript 在angularjs中将数据从服务传递给控制器
以下是我的服务代码-Javascript 在angularjs中将数据从服务传递给控制器,javascript,angularjs,angularjs-service,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) {
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
中期待会话数据
编辑
如果我使用的是
.then
,那么它将进入If
即If(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;
}
});
};
chkLogin是异步的。当您登录loginService.getInfo时,它还没有完成,所以它是空的。您应该从chkLogin函数返回一个promise对象。由于
chkLogin
是异步调用,getInfo
还没有被您尝试访问它的时间填充。@dfsq我正在查找这个,但您能帮我吗o在我的场景中适合这一点,因为我没有使用promise meforeshould call then()-它更详细,但它允许链接承诺。当然,我错过了这一点one@PatrickReck这段代码使我的页面每次刷新..某种递归