[英]Iron-router and Meteor.user: route called two times
我正在使用Iron路由器的onBeforeAction
方法來檢查用戶是否在除注冊和登錄路由以外的所有路由上登錄:
Router.onBeforeAction(function() {
if (!Meteor.user()) {
this.render('login');
}
else {
this.next();
}
}, {except: ['login', 'register']});
(僅供參考,使用以下代碼在登錄模板/ js中進行登錄過程)
這很好用,除了登錄后,登錄模板在被實際模板替換之前會快速顯示。
當我檢查正在發生的事情時,我發現Iron路由器之前Meteor.user()
尚未准備就緒。 結果,登錄頁面顯示為未登錄用戶。 然后(由於Meteor.user()
是反應性的),當Meteor.user()
准備就緒時,路由將再次運行,顯示正確的模板。
我如何才能使上面的代碼示例正常工作? (含義:由於Meteor.user()
未准備好而未顯示登錄模板)
我還在Stack Overflow上發現可以使用快速渲染程序包 ,但是我不願意破解渲染過程。 onRun()
方法也不能解決此問題。 我還在某個地方讀到了可以使用Router.configure
的waitOn
選項的地方,但是我僅有的示例是有關我還沒有的訂閱的示例(我正在使用不安全的自動發布包進行原型制作)。
我認為這不是最好的解決方案,但是這個技巧很好用:
Router.onBeforeAction(function() {
if (Meteor.user() !== undefined) {
if (!Meteor.user()) {
this.render('login');
}
else {
this.next();
}
}
else {
this.pause();
}
}, {except: ['login', 'register']});
此代碼示例有效,因為Meteor.user()
在准備就緒之前未定義 ,如果准備就緒但沒有用戶登錄,則為null 。
對於我的項目,我什至用加載屏幕替換了this.pause()
:
Router.onBeforeAction(function() {
if (Meteor.user() !== undefined) {
if (!Meteor.user()) {
this.render('login');
}
else {
this.next();
}
}
else {
this.render('loading');
}
}, {except: ['login', 'register']});
我希望這會幫助其他人。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.