未登录时路由到主屏幕

时间:2015-05-29 06:30:35

标签: meteor iron-router user-accounts

如果他们没有登录,我想将所有用户重定向到主页。目前我这样做:

Router.onBeforeAction(function() {
  this.render('loading');
  if (! Meteor.userId()) {
    this.render('Home');
  } else {
    this.next();
  }
});

我在网上看到的,但这似乎阻止我的'loading'模板显示,而是显示默认

  

加载...

位于屏幕的左上角。如果我将this.render('Home');更改为this.redirect('/'),我会看到正确的加载模板。但是,在'/'路线中,我调用了另一个this.render('Home'),我认为这会再次触发onBeforeAction,而'/'又将重定向到Router.onBeforeAction,这意味着您现在处于无限循环中负荷。

那么,正确的方法是修复我的Home以实现我的目标,即确保未登录的用户只能看到{{1}}模板,无论他们输入什么网址并做什么这没有弄乱我在网站其他地方的自定义加载模板?

2 个答案:

答案 0 :(得分:1)

如果用户未登录,我使用此onBeforeAction挂钩重定向到主页:

var userAuthHook = function() {
  if (Meteor.userId()) {
    //continue to the requested url
    this.next();
  } else {
    //redirect to home
    this.redirect('/');
  }
};

Router.onBeforeAction(userAuthHook, {
  except: ['home']
});

Router.route('/', {
  name: 'home'
});

请注意,我从钩子中排除主页以避免重定向循环,并且/路由在钩子排除中被称为“home”。

这对我有用,也允许使用加载模板。

答案 1 :(得分:1)

你需要有两个挂钩。一个用于'加载',一个用于检查用户是否已登录。

'loading'一个链接到您的订阅,通常是预装的带铁路由器的钩子。

Router.onBeforeAction(function() {
  if (! Meteor.userId()) {
    this.render('Home');
  } else {
    this.next();
  }
}, {except: ['route_one', 'route_two']});

Router.onBeforeAction('loading');

您的路线:

Router.route('/', {
    name: 'home',
    subscriptions: function() { 
        //Array of Meteor.subscribe to wait for and display the loading template
        return [Meteor.subscribe("a_subscription")]
    },
    loadingTemplate: 'loading',
    action: function() {
        this.render("Home_logged_in");
    }
});

所以在这里,如果Meteor.subscribe("a_subscription")正在加载,它将显示loading模板。如果用户已登录,则会显示Home_logged_in模板,如果未登录(在任何路线上)Home模板。

您还可以使用名称'route_one'和'route_two'为模板设置例外(您可以将其重命名为其他任何内容)。我将您的主页模板命名为home。但是,如果您将home添加到except列表,则onBeforeAction将不适用于home

相关问题