且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在用户刚刚登录或刚刚退出后重定向

更新时间:2023-12-03 15:07:58

这里是三个路由的例子:indexsignindashboard:

Router.configure({layoutTemplate: 'layout'});路由器映射(函数(){this.route('index', {path: '/'});this.route('登录');this.route('仪表板');});var mustBeSignedIn = 函数(暂停){if (!(Meteor.user() || Meteor.loggingIn())) {Router.go('登录');} 别的 {this.next();}};var goToDashboard = 函数(暂停){如果(流星.用户()){Router.go('仪表板');} 别的 {this.next();}};Router.onBeforeAction(mustBeSignedIn, {except: ['signin']});Router.onBeforeAction(goToDashboard, {only: ['index']});

如果用户在 index 页面上并且她已登录,她将自动被路由到 dashboard 页面.在除 signin 之外的任何页面上,如果用户未登录,她将被路由到 signin 页面.onBeforeAction 是反应性的,因此如果用户登录或退出,这些规则将立即执行.

当然你的路由会有所不同,但希望这个例子说明了一种使用铁路由器实现这一点的方法.

另见使用钩子 iron-router 指南的部分.>

It seems Deps.autorun is the way to go but Router.go doesn't seem to work within Deps.autorun.

Here is an example with three routes: index, signin and dashboard:

Router.configure({layoutTemplate: 'layout'});

Router.map(function() {
  this.route('index', {path: '/'});
  this.route('signin');
  this.route('dashboard');
});

var mustBeSignedIn = function(pause) {
  if (!(Meteor.user() || Meteor.loggingIn())) {
    Router.go('signin');
  } else {
    this.next();
  }
};

var goToDashboard = function(pause) {
  if (Meteor.user()) {
    Router.go('dashboard');
  } else {
    this.next();
  }
};

Router.onBeforeAction(mustBeSignedIn, {except: ['signin']});
Router.onBeforeAction(goToDashboard, {only: ['index']});

If a user is on the index page and she is logged in, she will automatically be routed to the dashboard page. On any page except for signin, if the user is not logged in she will be routed to the signin page. onBeforeAction is reactive so these rules will be enforced immediately if the user logs in or out.

Of course your routes will be different, but hopefully this example illustrates one way to make this work with iron-router.

Also see the using hooks section of the iron-router guide.