我在登录系统上遇到此问题: 服务menuService上的属性未更新。
工作流: 在成功的帖子登录后,我正在更改变量menuService.isUserLoggedIn,但是没有正确更新,正如您在console.log上看到的那样。我做错了什么/或者错过了什么?
代码:
app.factory('menuService', function(){
return {
isUserLoggedIn: false,
}
})
app.factory('userService', function($http, menuService){
var doLogin = function(user){
$http.post('/login', user)
.success(function(data, status, header, config){
menuService.isUserLoggedIn = true
})
.error(function(data, status, header, config){
console.log('Error ' + data)
})
}
return {
doLogin: doLogin
}
})
app.controller('LoginController', function($scope, userService, menuService){
$scope.user = {}
$scope.doLogin = function(user){
console.log(menuService.isUserLoggedIn) //FALSE
userService.doLogin(user)
console.log(menuService.isUserLoggedIn) //FALSE BUT I think should be TRUE
}
})
答案 0 :(得分:0)
$http.post()
是异步的,因此您需要返回其承诺并使用.then()
方法检查完成后的值...
app.factory('userService', function($http, menuService){
var doLogin = function(user){
return $http.post('/login', user)
.then(function(){
menuService.isUserLoggedIn = true
}, function(response){
console.log('Error ' + response.data)
});
};
return {
doLogin: doLogin
}
})
app.controller('LoginController', function($scope, userService, menuService){
$scope.user = {}
$scope.doLogin = function(user){
console.log(menuService.isUserLoggedIn) //FALSE
menuService.doLogin(user).then(function() {
console.log(menuService.isUserLoggedIn);
});
}
})