[英]Roles.userIsInRole returns FALSE - Meteor
使用im FlowRouter
與FlowTemplate
和both/router/router.js
我檢查是用戶角色admin
:
....
action: function () {
if(Roles.userIsInRole(Meteor.userId(), 'admin')){
FlowLayout.render('layout', {
sidebar: 'sidebar', main:'admin', cart:'cart'
})
} else {
FlowLayout.render('layout', {
sidebar: 'sidebar', main:'unauthorised', cart:'cart'
})
}
console.log(Meteor.userId());
}
....
並返回FALSE
,但是當我在WEB控制台中使用它時為TRUE
。 這行console.log(Meteor.userId());
輸出正確的userID
,當我登錄時,如果我在WEB控制台Roles.userIsInRole(Meteor.userId(), 'admin')
,則為TRUE
。 如果我這樣做Meteor.user().roles
,結果是['admin']
如果我簽入模板是用戶角色:
{{#if isInRole 'admin' }}
ADMIN
{{/if}}
它是TRUE
,但在router.js
返回FALSE
。
怎么解決?
roles
字段很可能是在稍后階段(基於不同的訂閱)接收的。
您應該確保此訂閱已准備好 - 直接或通過使用其他一些機制來確保您獲得該字段(例如確保它是一個數組),然后才進行路由/呈現決策。
是的,聽起來像我遇到的時間問題。 我必須解決的2種競爭條件(一種是使用AccountsTemplates,另一種是角色已經准備好)。 它在這里討論:
https://github.com/kadirahq/flow-router/issues/608
這是我的解決方案。 它位於routes.js的頂部:
import {Tracker} from 'meteor/tracker';
if (Meteor.isClient) {
FlowRouter.wait();
let tracker;
let self = this;
self.getATReady = () => AccountsTemplates._initialized;
let timer = Meteor.setInterval(function() {
if (self.getATReady()) {
tracker.invalidate();
clearInterval(timer);
}
}, 500);
tracker = Tracker.autorun(function() {
if (!FlowRouter._initialized && Roles.subscription.ready() && self.getATReady()) {
clearInterval(timer);
FlowRouter.initialize();
}
});
}
基本上,這個代碼阻止了FlowRouter的初始化,直到角色和AccountsTemplates都准備好了。 一旦他們准備好了,FR就會被初始化,你可以使用你的路線知道你可以檢查角色。
自2016年8月以來,我已經在幾個Meteor版本中進行了此修復,並且我沒有看到問題再次發生。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.