流星-使用ui-router加载状态之前的调用函数 [英] Meteor - Call function before state loaded using ui-router
问题描述
我们正在制作一个使用角度和ui-router来控制状态的流星应用程序.如果用户无权访问网站的主要部分,我们希望显示一个促销网站.在mongodb的User集合中的用户文档上将有一个标志,表明他们是否有权访问.
We're making a meteor app using angular and ui-router to control the states. We want to show a promo site if the user doesn't have access to the main part of the site. There will be a flag on the user's document in the User collection in mongodb as to whether they have access or not.
如果他们没有访问权限,那么在加载状态之前,我们如何将其定向到此促销状态?基本流程将是调用一个函数以检查它们是否具有访问权限,然后根据该状态加载状态.
How would we direct to this promo state before a state is loaded if they don't have access? The basic flow would be calling a function to check whether they have access, and then loading a state based on that.
推荐答案
在受保护页面的路由(在我的情况下,是一组受保护页面的父级)中,输入以下内容:
In the route for the protected page (or in my case the parent of a set of protected pages), put this:
.state('app', {
abstract: true,
template: '<mymenu></mymenu>',
controller: Menu,
resolve: {
currentUser: ($q) => {
var deferred = $q.defer();
Meteor.autorun(function () {
if (!Meteor.loggingIn()) {
if (Meteor.user() == null) {
deferred.reject('AUTH_REQUIRED');
} else {
deferred.resolve(Meteor.user());
}
}
});
return deferred.promise;
}
}
});
解决部分将拒绝该路由(请参见下面的处理程序),并确保在激活路由之前已完全加载Meteor.user().
The resolve part will reject the route (see below for the handler), and also ensure that Meteor.user() is fully loaded before activating the route.
将此处理程序放入您的.run方法中:
Put this handler in your .run method:
function run($rootScope, $state) {
'ngInject';
$rootScope.$on('$stateChangeError',
(event, toState, toParams, fromState, fromParams, error) => {
console.log("$stateChangeError: "+error);
if (error === 'AUTH_REQUIRED') {
$state.go('login');
}
}
);
}
它将重定向您到登录页面(或您选择的任何其他页面)
It will redirect you to the login page (or any other page of your choice)
这篇关于流星-使用ui-router加载状态之前的调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!