【问题标题】:Roles.userIsInRole returns FALSE - MeteorRoles.userIsInRole 返回 FALSE - Meteor
【发布时间】:2017-11-05 14:35:03
【问题描述】:

我正在使用FlowRouterFlowTemplateboth/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

如何解决?

【问题讨论】:

    标签: javascript meteor meteor-accounts


    【解决方案1】:

    roles 字段可能会在稍后阶段收到(基于不同的订阅)。

    您应该确保此订阅已准备就绪 - 直接或通过使用其他机制来确保您获得该字段(例如确保它是一个数组),然后才做出路由/渲染决策.

    【讨论】:

      【解决方案2】:

      是的,听起来像是我遇到的时间问题。我必须解决 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();
              }
          });
      }
      

      基本上,在角色和 AccountsTemplate 都准备好之前,此代码会阻止 FlowRouter 的初始化。一旦它们都准备好了,FR 就被初始化了,你可以使用你的路由知道你可以检查角色。

      自 2016 年 8 月以来,我已经在多个 Meteor 版本中进行了此修复,但我没有看到问题再次出现。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-05-08
        • 2019-06-27
        • 1970-01-01
        • 1970-01-01
        • 2014-10-18
        • 2015-08-02
        • 2012-05-17
        相关资源
        最近更新 更多