我正在写一些小练习来教我自己AngularJS和我正在尝试写一些简单的用户授权任务。我有一个表单来收集/输入用户名和密码,然后使用$http
和CORS(因为我的REST服务在另一个端口上运行)将它们发送到休息服务,它们会被检查,如果有匹配,我会返回一个UUID并创建一个令牌,然后我的登录值为$rootScope
上的true,就像这样。更新AngularJS当用户操作完成时查看
// this is in a service I call 'authService'
this.login = function (user) {
return $http({method: 'POST', url: 'http://127.0.0.1:3000/login', data: user})
.then(function (response) {
// set up a local storage token
storageService.setLocalStorage('token', response.data[0].uuid);
// broadCast is loggedIn - we have a match
$rootScope.loggedInUser = true; // this is set to false at the .run() of the app
$rootScope.$broadcast('LoggedIn');
return 1;
}, function() {
// return http code later
return 0;
});
};
this.getLoggedIn = function() {
return $rootScope.loggedInUser;
};
在单独的菜单视图我有以下条件
现在(在authService添加为菜单控制器上的扶养):
<div id="logIn" ng-show="!authService.getLoggedIn()">...</div>
现在,当我加载的应用程序的第一次的条件是正确的,但是我希望这个条件更新,如果用户登录正确(所以div)不显示。在菜单控制器中我有下面的代码,它似乎没有任何事情做?
$scope.$on('LoggedIn', function() {
authService.getLoggedIn(); // doesn't update the view?
console.log($rootScope.loggedInUser); // returns true
console.log(authService.getLoggedIn()); // returns true
});
$scope.$watch('loggedInUser', function() {
console.log('loggedInUser has changed ' + $rootScope.loggedInUser);
// This runs once when we set $rootScope.loggedInUser in the .run() of the app, output is: 'loggedInUser has changed false'
// then when we have successfully logged in again, output is 'loggedInUser has changed true'
});
好了,所以当我改变了$ rootScope.loggedInUser,我做错了什么,我的做法在我的菜单视图的<div>
条件不更新,能有人给我一些建议或纠正我的这个方法。谢谢
' ng-show'绑定到一个范围值,比如'$ scope.isLogon'或一个返回true或false的范围函数。 'authService.getLoggedIn()'没有被定义,或者至少不在你在这里展示的代码中。所以意味着'authService.getLoggedIn()'总是为false。 – wayne
对不起,authService.getLoggedIn()是在一个服务中定义的,我将其添加为菜单控制器的依赖关系,因此当我登录console.log(authService.getLoggedIn())时;和$ scope。$ watch('loggedInUser'function(){})在控制器中被触发,但视图不被更新? –
该视图不能访问authService,您可以在菜单控制器中执行代理'authService.getLoggedIn()'。像'$范围。 getAuth = function(){return authService.getLoggedIn()}'。我也不认为需要将rootScope引入您的用例。 – wayne