Вопрос

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.

Другие советы

A few things above seem to be outdated. Here's how I got things working at the present time:

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

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

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

Router.onBeforeAction(mustBeSignedIn, {except: ['login']});
Router.onBeforeAction(goHome, {only: ['index', 'login']});
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();
  }
};

FYI, pause( ) is no supported now, just replace with this.next( )

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top