问题描述
我正在将 AngularJS 与 Meteor 结合使用,并希望将使用未经验证的电子邮件的用户重定向到登录页面.我在 /client/routes.js
中创建了一个登录视图:
I am using AngularJS with Meteor and wanted to redirect users with unverified emails to the sign in page. I have created a sign in view in /client/routes.js
:
app.config(['$stateProvider', '$urlRouterProvider',
function($stateProvider, $urlRouterProvider){
$urlRouterProvider.otherwise('/');
$stateProvider
.state('signin', {
url:'/signin',
views: {
main: {
templateUrl: 'client/views/profile/signin.tpl'
}
}
})
请注意,为了简洁起见,我没有列出其他州.
Note that there are other states I am not listing for brevity sake.
现在,如果用户的电子邮件未经验证,我想将用户重定向到此登录页面.如何从 UI-Router FAQs 来满足我的需求?我可以接受不使用以下示例的其他解决方案,只要它们能解决手头的问题.
Now, I want to redirect users to this sign in page if their emails have not been verified. How do I modify the example below from UI-Router FAQs to meet my needs? Other solutions not using the example below are acceptable to me as long as they address the issue at hand.
示例:使用状态配置上的数据对象来定义规则将针对用户运行逻辑的函数(此处使用示例名为 $currentUser 的服务).$stateChangeStart 处理程序捕获所有状态转换并在允许之前执行此规则检查转换,可能会阻止它和/或重定向到不同的状态.
app.config(function($stateProvider) {
$stateProvider.state('privatePage', {
data: {
rule: function(user) {
// ...
}
});
});
app.run(function($rootScope, $state, $currentUser) {
$rootScope.$on('$stateChangeStart', function(e, to) {
if (!angular.isFunction(to.data.rule)) return;
var result = to.data.rule($currentUser);
if (result && result.to) {
e.preventDefault();
// Optionally set option.notify to false if you don't want
// to retrigger another $stateChangeStart event
$state.go(result.to, result.params, {notify: false});
}
});
});
推荐答案
FAQ 中的示例尝试创建一种向任何页面添加规则的通用方法.让我们保持简单:
The example from the FAQ attempts to create a general way to add a rule to any page. Let's keep it simple:
app.run(function($rootScope, $state, UserService) {
$rootScope.$on('$stateChangeStart', function(event, toState) {
// don't check auth on login routes
if (["signin"].indexOf(toState.name) === -1) {
if (UserService.doesNotHaveVerifiedEmail()) {
event.preventDefault();
$state.go('signin');
return;
}
}
}
});
任何时候加载状态并且它不是 signin 状态,您检查用户是否已验证(取决于您的应用程序,这里我注入一个 UserService,我假设它了解用户的状态) 否则,您可以阻止该状态更改并将其重定向到登录页面.
Anytime a state is loaded and it's not the signin state, you check if the user is verified (depends on your application, here I am injecting a UserService which I assume has knowledge about the user's status) and if not, you prevent that state change and redirect them to the signin page.
这篇关于如何使用 Angular UI-Router 使用未经验证的电子邮件重定向用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!