[英]Waiting on Meteor.user()
If a new users signs up, I take them to the getting started route so they enter can enter a name which is at /gs
. 如果有新用户注册,我将带他们进入入门路线,因此他们输入的名称可以输入/gs
。 I store the name inside a name property of the profile object of the current user. 我将名称存储在当前用户的配置文件对象的名称属性内。 Now if a user who has already entered a name and visits the /gs
route I want to redirect them to the root. 现在,如果已经输入名称并访问/gs
路由的用户,我想将其重定向到根目录。 In iron router, I do this: 在铁路由器中,我这样做:
Router.route('/gs', {
name: 'gs',
onBeforeAction: function() {
if ( Meteor.user().profile.name ) {
this.redirect('/');
} else {
this.render();
}
}
});
Even though this works, it prints out 2 errors to the console. 即使这可行,它也会向控制台输出2个错误。 One of them being "Cannot read property 'profile' of undefined" and the lack of this.next()
. 其中之一是“无法读取未定义的属性'profile'”和缺少this.next()
。 Any way to fix these problems. 解决这些问题的任何方法。
Your route functions and most hooks are run in a reactive computation. 您的路由功能和大多数挂钩都在反应式计算中运行。 This means they will rerun automatically if a reactive data source changes. 这意味着如果反应性数据源发生更改,它们将自动重新运行。 For example, if you call Meteor.user() inside of your route function, your route function will rerun each time the value of Meteor.user() changes. 例如,如果您在route函数内部调用Meteor.user(),则每次Meteor.user()的值更改时,route函数都会重新运行。 ( Iron.Router Guide: Reactivity ) ( Iron.Router指南:反应性 )
Hook functions and all functions that get run when dispatching to a route are run in a reactive computation: they will rerun if any reactive data sources invalidate the computation. 挂钩函数和在路由分配时运行的所有函数均在反应式计算中运行:如果任何反应式数据源使计算无效,它们将重新运行。 In the above example, if Meteor.user() changes the entire set of route functions will be run again. 在上面的示例中,如果Meteor.user()更改,则会再次运行整个路由功能集。 ( Iron.Router Guide: Using Hooks ) ( Iron.Router指南:使用挂钩 )
The first time the function is run, Meteor.user()
is undefined
. 第一次运行该函数时, Meteor.user()
是undefined
。 Then its value change to an object. 然后其值更改为一个对象。 As it is a reactive variable, the function is run again, without error this time. 由于它是一个反应变量,因此该函数将再次运行,这次没有错误。
You should check if Meteor.user()
is defined before using its properties. 在使用Meteor.user()
的属性之前,应检查是否已定义。 Here is a very (maybe too much) exhaustive way of doing so: 这是一种非常(可能太多)的方法:
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 has the correct answer, wanted to share my working code! 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.