【问题标题】:Doing something different for main route in meteor iron router在流星铁路由器中为主路由做一些不同的事情
【发布时间】:2015-09-27 23:00:37
【问题描述】:

我在我的流星应用程序中使用 Iron-Route 进行路由。由于我有多个模块并且我想避免多个编码,因此我将用于身份验证(角色)的过滤器放入核心包中:

核心包

var filters = {
    authenticate: function () {
        var user;
        if (Meteor.loggingIn()) {
            this.layout('login');
            this.render('loading');
        } else {
            user = Meteor.user();
            if (!user) {
                this.layout('login');
                this.render('signin');
                return;
            }
            this.layout('StandardLayout');
            this.next();
        }
    }
}
Router.configure({
    layoutTemplate: 'layout',
    loadingTemplate: 'loading',
    notFoundTemplate: 'notFound',
    before: filters.authenticate
});
Router.route('/', function () {
    this.render('contentTemplate', { to: 'content' });
    this.render('navigationTemplate', { to: 'navigation' },)
});

其他包

...只需要这个:

Router.route('/article/:_id', {
    name: 'article',
    yieldTemplates: {
        'navigationPage':   { to: 'navigation' },
        'contentPage':      { to: 'content' } 
    }
});

现在在显示任何内容之前都会检查每个模块(路线)。 但我需要头版例外。主页Route.route('/') 也应该由未登录的用户访问。我该怎么做?

【问题讨论】:

    标签: javascript meteor iron-router


    【解决方案1】:

    您可以使用iron:router 中的onBeforeAction 挂钩,如下所示。 此解决方案假定您的登录路径名为 'login' 。但可以根据您的需要进行修改。

    ./client/lib/hooks/router.js

    Router.onBeforeAction(function () {
        // all properties available in the route function
        // are also available here such as this.params
        if  (!Meteor.userId()) {
            //code for action to be taken when user is not logged in
            this.redirect('login');
            this.stop();
        } else {
            this.next();
        }
    },{except: ['homeRouteName'] });
    

    注意:将 'homeRouteName' 替换为您在 '/' 的路线名称

    【讨论】:

    • 所以我可以把现在在过滤器变量中的代码放在那里,对吧?
    • 我没试过,但你可能可以。关键是{except: ['routes']} 选项,它允许您指定哪些路由不运行此挂钩。或者,您可以只使用{only: ['routes']} 以获得相反的效果。我建议您的情况除外,因为您只希望它不在一个上运行。
    猜你喜欢
    • 2014-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-22
    • 2015-08-11
    • 2016-09-22
    • 2014-09-07
    相关资源
    最近更新 更多