您已经在使用 cookie - 服务器正在设置它们。你所做的是一种相当标准的做事方式。
要检查 json 文件,您可以在控制器中执行类似于此存根显示的操作:
app.controller('AppControl', function($scope, $http, $location){
// Get the JSON file.
$http.get('/path/to/json/file')
.then(response){
if(response.data.error){
// redirect to login
$location.path('login');
}
else{
$scope.user = response.data;
// your app code here.
}
})
.catch(function (error){
// unable to reach the json file - handle this.
});
});
当然,你真的应该把它移到服务中,这样你就可以重复使用它,并且缓存数据,而不是每次更改路由/页面时都获取用户,但这会给你一个模糊的概念。
编辑示例工厂:
.factory('User', function( $http ){
// Create a user object - this is ultimately what the factory will return.
// it's a singleton, so there will only ever by one instance of it.
var user = {};
// NOTE: I am assigning the "then" function of the login promise to
// "whenLoggedIn" - your controller code is then very easy to read.
user.whenLoggedIn = $http.get('user.json')
.then(function(response){
// Check to see if there is an error.
if (response.data.error !== undefined) {
// You could be more thorough with this check to determine the
// correct action (examine the error)
user.loggedIn = false;
}
else {
// the user is logged in
user.loggedIn = true;
user.details = response.data;
return user;
}
}).then; // <-- make sure you understand why that .then is there.
return user;
})
在控制器中的使用
.controller('ExampleController', function($scope, User){
// It's handy to have the user on the scope - you can use it in your markup
// like I have with ng-show on index.html.
$scope.User = User;
// Do stuff only if the user is loggedin.
// See how neat this is because of the use of the .then function
User.whenLoggedIn( function (user){
console.log(user.details.name + " is logged in");
});
});
因为它在作用域上,我们可以在 html 中这样做:
<body ng-controller="ExampleController">
<h1 ng-show="User.loggedIn == null">Logging in..</h1>
<h1 ng-show="User.loggedIn == true">Logged in as {{ User.details.name }}</h1>
<h1 ng-show="User.loggedIn == false">Not logged in</h1>
</body>
这是一个example on plunker,它正在工作。
注意以下几点:
如果用户已经/已经登录,当你以后注入服务时,它不会再次检查文件。您可以在服务上创建其他方法来重新检查文件,并将用户注销、重新登录等。我将由您决定。
还有其他方法可以做到这一点 - 这只是一种可能的选择!
这可能很明显,但总是值得一提。您需要主要处理服务器端的身份验证和安全性。客户端只是用户体验,并确保用户不会看到混乱或冲突的屏幕。