【问题标题】:this.userId returns undefined inside Meteor.publishthis.userId 在 Meteor.publish 中返回 undefined
【发布时间】:2015-01-16 19:12:33
【问题描述】:

在我的Meteor.publish() 函数之一中,this.userId 的值为undefined。我不能打电话给Meteor.userId(),因为它是not available inside a publish function。你现在应该如何获得userId

【问题讨论】:

    标签: javascript meteor publish userid


    【解决方案1】:

    有四种可能:

    1. 没有用户登录。

    2. 您正在从服务器调用该方法,因此不会有与该调用关联的用户(除非您是从另一个具有用户绑定的函数中调用它到它的环境,比如另一个方法或订阅函数)。

    3. 您甚至没有安装 accounts-base 软件包(或任何附加组件)。我只是为了完整起见。

    4. 您在 ES6 中使用箭头函数。 Meteor.publish('invoices', function() { return invoices.find({by: this.userId}); }); 可以正常工作,而 Meteor.publish('invoices', () => { return invoices.find({by: this.userId}); }); 将返回一个空游标,因为 this 将没有 userId 属性。 这是因为箭头函数没有绑定自己的thisargumentssupernew.target

    如果肯定不是 (2),那么当您在客户端上进行方法调用之前立即登录 Meteor.userId() 会发生什么?

    【讨论】:

    • 是的,它是 2。我在 Meteor.publish 上方设置了 var = this.userId,所以它是从服务器调用的。将其移入Meteor.publish 修复了它。谢谢!
    • 另外,为了完整起见,请确保您没有使用箭头功能,即Meteor.publish('invoices', function() { return invoices.find({by: this.userId}); }); 可以正常工作,而Meteor.publish('invoices', () => { return invoices.find({by: this.userId}); }); 将返回空光标,因为它没有用户 ID。因为箭头函数“不绑定它自己的 this、arguments、super 或 new.target”。
    • @ElijahSaounkine 谢谢!受 ES6 影响。
    • 这是粗箭头。谢谢!
    • 干杯这让我发疯了,我是 4。
    【解决方案2】:
    FIXED:
    
    import { Meteor } from 'meteor/meteor';
    import { Roles } from 'meteor/alanning:roles';
    import _ from 'lodash';
    
    import { check } from 'meteor/check';
    
    
    import Corporations from '../corporations';
    
    Meteor.publish('corporations.list', () => {
      const self = this.Meteor; // <-- see here 
      const userId = self.userId();
      const user = self.user();
    
      let filters = {};
    
      if (user) {
        if (!Roles.userIsInRole(userId, ['SuperAdminHolos'])) { // No Está en el Rol SuperAdminHolos
          filters = { adminsEmails: { $in: _.map(user.emails, 'address') } };
        }
        return Corporations.find(filters);
      } else return;
    });
    

    【讨论】:

      【解决方案3】:

      您应该改用 Meteor.userId()。

      【讨论】:

      • 它说“错误:Meteor.userId 只能在方法调用中调用。在发布函数中使用 this.userId。”
      • Meteor.publish("my_channel", function() { var userId = this.userId; myFunction(userId); });
      • this.userId 未定义
      • Meteor.publish() 无权访问Meteor.userId(): docs.meteor.com/#/full/meteor_userid "除发布功能外的任何地方"
      猜你喜欢
      • 1970-01-01
      • 2018-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-06
      • 2021-06-24
      相关资源
      最近更新 更多