在我的应用程序中更改视图时,我创建了resolve函数,该函数应该确定用户是否已登录:
$routeProvider.
when('/taskoverview', {
templateUrl: 'Home/Template/taskoverview', resolve: TaskOverviewCtrl.resolve, access: { allowAnonymous: true },
resolve: {
userAuthenticated: ["$http", function ($http) {
var loggedIn;
$http.get('/api/Authentication/UserAuthenticated').then(function (data) {
if (data.data != null) {
loggedIn = true;
}
else {
loggedIn = false;
console.log("really");
}
});
return loggedIn;
}]
}
}).
otherwise({ redirectTo: '/' });
发生这种情况后,我想在locationChangeStart上检查userAuthenticated的值,所以我认为它应该是非常向前的。
WorkerApp.run(function ($rootScope, $routeParams, $route, $location) {
$rootScope.$on('$locationChangeStart', function (event, next, current) {
for (var i in $route.routes) {
if (next.indexOf(i) != -1) {
if ($route.routes[i].access != null && ($route.routes[i].userAuthenticated != null || typeof($route.routes[i].userAuthenticated) != "undefined")) {
if ((!$route.routes[i].access.allowAnonymous || $route.routes[i].access.allowAnonymous == "undefined") && (!$route.routes[i].userAuthenticated || $route.routes[i].userAuthenticated == "undefined")) {
event.preventDefault();
alert("no access");
}
}
}
}
});
});
但是evrytime我改变了我的userAuthenticated总是未定义的。所以问题是,我如何让它返回一个值?
有没有更直接的方法来阻止用户访问未经过身份验证的页面?
答案 0 :(得分:1)
试试这个:
$routeProvider.
when('/taskoverview', {
templateUrl: 'Home/Template/taskoverview', resolve: TaskOverviewCtrl.resolve, access: { allowAnonymous: true },
resolve: {
userAuthenticated: ["$http", "$q", function ($http, $q) {
var deferred = $q;
$http.get('/api/Authentication/UserAuthenticated').then(function (data) {
if (data.data != null) {
deferred.resolve();
}
else {
deferred.reject();
console.log("really");
}
});
return deferred.promise;
}]
}
}).
otherwise({ redirectTo: '/' });
如果你想处理拒绝,你可以为“$ routeChangeError”事件创建一个$ on侦听器,如下所示:
$rootScope.$on("$routeChangeError", function (event, current, previous, rejection) {
alert("Not authorised");
}