繁体   English   中英

等待Meteor.user()

[英]Waiting on Meteor.user()

如果有新用户注册,我将带他们进入入门路线,因此他们输入的名称可以输入/gs 我将名称存储在当前用户的配置文件对象的名称属性内。 现在,如果已经输入名称并访问/gs路由的用户,我想将其重定向到根目录。 在铁路由器中,我这样做:

Router.route('/gs', {
  name: 'gs',
  onBeforeAction: function() {
    if ( Meteor.user().profile.name ) {
      this.redirect('/');
    } else {
      this.render();
    }
  }
});

即使这可行,它也会向控制台输出2个错误。 其中之一是“无法读取未定义的属性'profile'”和缺少this.next() 解决这些问题的任何方法。

您的路由功能和大多数挂钩都在反应式计算中运行。 这意味着如果反应性数据源发生更改,它们将自动重新运行。 例如,如果您在route函数内部调用Meteor.user(),则每次Meteor.user()的值更改时,route函数都会重新运行。 Iron.Router指南:反应性

挂钩函数和在路由分配时运行的所有函数均在反应式计算中运行:如果任何反应式数据源使计算无效,它们将重新运行。 在上面的示例中,如果Meteor.user()更改,则会再次运行整个路由功能集。 Iron.Router指南:使用挂钩

第一次运行该函数时, Meteor.user()undefined 然后其值更改为一个对象。 由于它是一个反应变量,因此该函数将再次运行,这次没有错误。

在使用Meteor.user()的属性之前,应检查是否已定义。 这是一种非常(可能太多)的方法:

if (Meteor.user() !== undefined) {
  // the user is ready
  if (Meteor.user()) {
    // the user is logged in
    if (Meteor.user() && Meteor.user().profile.name) {
      // the name is already set
      this.redirect('/');
    } else {
      this.render();
  } else {
    // the user is not logged in
} else {
  // waiting for the user to be ready
}

Pandark的答案正确,想分享我的工作代码!

Router.route('/account',{
fastRender: true,
data:function(){

    if( Meteor.user() && Meteor.user().profile.guest ){
        Router.go('/login');
    } else {
        Router.go('/account');
    }
},
template:'screen',
yieldTemplates: {
    'account': {to: 'content'},
}
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM