2017-06-04 41 views
0

進出口使用FlowRouterFlowTemplateboth/router/router.js我檢查是用戶角色adminRoles.userIsInRole返回FALSE - 流星

.... 
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

如何解決?

回答

2

roles字段很可能是在稍後階段(基於不同的訂閱)收到的。

您應該確保此訂閱已準備就緒 - 可以直接或通過使用其他一些機制來確保您獲得該字段(例如確保它是一個數組),然後才能進行路由/呈現決策。

1

是的,聽起來像我遇到的時機問題。 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版本,並且我沒有看到問題重演。