[英]Resolve user data after full page reload in AngularJS
In my angular application, after full page reload happens, I want to be able to retrieve the user information via $http.get and if the user is logged in($http.get returns user info) then I want to show the 'about me' page, if user is not logged in then they should see the login page. 在我的角度应用程序中,在重新加载整个页面之后,我希望能够通过$ http.get检索用户信息,如果用户已登录($ http.get返回用户信息),那么我想显示“关于我”页面上,如果用户未登录,则应该看到登录页面。
Currently I tried doing this in application.run method as shown in the code below, but since $http is async, the $rootScope.currentUser does not get set for some time and I get transferred to the login page by my $routeChangeStart event handler even when i'm logged in. 目前,我尝试在application.run方法中执行此操作,如下面的代码所示,但是由于$ http是异步的,因此$ rootScope.currentUser一段时间未设置,并且我的$ routeChangeStart事件处理程序将其转移到登录页面即使我已经登录。
myAPp.config(function ($routeProvider) {
$routeProvider.when('/', {
templateUrl: '/app/homeView/home.html',
controller: 'HomeViewController'
}).when('/login', {
templateUrl: '/app/loginView/login.html',
controller: 'LoginController'
}).when('/me', {
templateUrl: '/app/userInfoView/userInfo.html',
controller: 'UserInfoController',
access: {
requiresLogin: true
}
}).otherwise({
redirectTo: '/'
});
}
);
myApp.run(function ($rootScope, $cookies, $location, UserService) {
UserService.getCurrentUser().then(
function (response) {
$rootScope.currentUser = response;
},
function () {
$rootScope.currentUser = null;
}
);
$rootScope.$on('$routeChangeStart', function (event, next) {
if (next.access !== undefined) {
if (next.access.requiresLogin && !$rootScope.currentUser) {
$location.path('/login');
} else {
$location.path('/me');
}
}
});
});
What is the correct way to solve this problem? 解决此问题的正确方法是什么?
Following what @FuzzyTree started the following should do what you need 跟随@FuzzyTree开始的内容之后,以下应完成您需要的操作
myApp.run(function($rootScope, $cookies, $location, UserService) {
var userPromise = UserService.getCurrentUser().then(
function(response) {
$rootScope.currentUser = response;
},
function() {
$rootScope.currentUser = null;
}
);
$rootScope.$on('$routeChangeStart', function(event, next) {
if (next.access !== undefined) {
if (next.access.requiresLogin && !$rootScope.currentUser) {
// prevent this change
event.preventDefault();
// let user promise determine which way to go
userPromise.then(function() {
// will call another `$routeChangeStart` but
// that one will pass around the above conditional
$location.path('/me');// modify using `next.url` if app gets more robust
}).catch(function() {
$location.path('/login');
});
}
}
});
});
you can: 您可以:
check user then bootstrap angular application https://docs.angularjs.org/api/ng/function/angular.bootstrap 检查用户然后引导角度应用程序https://docs.angularjs.org/api/ng/function/angular.bootstrap
show state loading until user checking is over 显示状态加载,直到用户检查结束
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.