我有一个带登录按钮的布局页面,我只想在我没有登录时显示它。我想通过使用服务实现这一点:
app.service('AuthService', function ($http) {
this.getUserStatus = function () {
return $http({
url: '/auth/status',
method: "GET"
});
};
});
然后我在控制器中调用它:
app.controller('MenuController', [
'$scope',
'$http',
function ($scope, AuthService) {
$scope.authorize = function() {
AuthService.getUserStatus();
}
}
]);
最后,我在布局中使用ng-controller和ng-hide来显示或隐藏注销按钮:
<body ng-app="headcountApp">
<nav ng-controller="MenuController">
<ul>
<li ng-hide="authorize">
<a href="#/">Login</a>
</li>
<li>
<a href="#/employee/add">Add</a>
</li>
<li>
<a href="#/employees">employees</a>
</li>
<li>
<a href="#/edit">Edit</a>
</li>
<li>
<a href="#/delete">Delete</a>
</li>
<li>
<a href="/logout">logout</a>
</li>
</ul>
</nav>
我的问题是它总是被隐藏,告诉我价值永远是真的。我该如何解决这个问题?
这解决了问题:
app.controller('MenuController', [
'$scope',
'$http',
'AuthService',
function ($scope, $http, AuthService) {
$scope.authorized = false;
AuthService.getUserStatus().then(function(res){
$scope.authorized = res.data;
});
}
]);
答案 0 :(得分:2)
AuthService.getUserStatus();
返回$http()的结果。 $http()
来电的结果是promise。你需要注册一个带有promise的解决回调来获得http请求的结果:
$scope.authorized = false;
$scope.authorize = function() {
AuthService.getUserStatus().then(function(res){
// If result from server indicate login state set $scope.authorized = true
});
}
在您的视图中绑定到$scope.authorize
:
<li ng-hide="authorized">
<a href="#/">Login</a>
</li>