【发布时间】:2015-01-16 19:12:33
【问题描述】:
在我的Meteor.publish() 函数之一中,this.userId 的值为undefined。我不能打电话给Meteor.userId(),因为它是not available inside a publish function。你现在应该如何获得userId?
【问题讨论】:
标签: javascript meteor publish userid
在我的Meteor.publish() 函数之一中,this.userId 的值为undefined。我不能打电话给Meteor.userId(),因为它是not available inside a publish function。你现在应该如何获得userId?
【问题讨论】:
标签: javascript meteor publish userid
有四种可能:
没有用户登录。
您正在从服务器调用该方法,因此不会有与该调用关联的用户(除非您是从另一个具有用户绑定的函数中调用它到它的环境,比如另一个方法或订阅函数)。
您甚至没有安装 accounts-base 软件包(或任何附加组件)。我只是为了完整起见。
您在 ES6 中使用箭头函数。
Meteor.publish('invoices', function() { return invoices.find({by: this.userId}); }); 可以正常工作,而 Meteor.publish('invoices', () => { return invoices.find({by: this.userId}); }); 将返回一个空游标,因为 this 将没有 userId 属性。
这是因为箭头函数没有绑定自己的this、arguments、super 或new.target。
如果肯定不是 (2),那么当您在客户端上进行方法调用之前立即登录 Meteor.userId() 会发生什么?
【讨论】:
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”。
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;
});
【讨论】:
您应该改用 Meteor.userId()。
【讨论】:
Meteor.publish() 无权访问Meteor.userId(): docs.meteor.com/#/full/meteor_userid "除发布功能外的任何地方"