[英]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.