因此,我正在创建一个用户个人资料页面,并已获取当前用户的所有数据,工作正常。我遇到的问题是当前用户无法看到其他用户的数据。
我已经查看了网上可以找到的所有内容,但没有找到对我有帮助的答案,只是做一件事有很多不同的方法。
我的发布
Meteor.publish('allUsers', function(user){
return Meteor.users.find({_id: this.userId},{
fields: {
profile: 1,
emails:1,
username: 1
}
});
});
我的路由器
Router.route('/profile/:_id', {
name: 'profile',
waitOn: function(){
return Meteor.subscribe('allUsers')},
data: function(){
var user = this.params._id;
return Meteor.users.findOne({_id: user});
},
});
个人资料模板
<template name='profile'>
Username: {{username}}<br>
Email: {{email}}
{{log}}
{{#with profile}}
Full Name: {{name}}
{{log}}
{{/with}}
</template>
helper
Template.profile.helpers({
name: function(){
return this.name;
},
username: function(){
return this.username;
},
email: function(){
return this.emails[0].address;
},
log: function(){
console.log(this);
}
});
这就是我链接到其他用户的方式
<a href="/profile/{{owner}}">{{username}}</a>
所有者是用户_id:
当前用户的日志输出正在显示数据,但其他用户的日志输出是空对象。尽管它正在获取正确的_id。
最佳答案
在您的 allUsers
出版物中,您可以找到具有 {_id: this.userId}
的用户。 this.userId
是订阅用户的 ID。这意味着您正在发布用户自己的数据,而不是任何其他用户的数据。如果您想发布所有用户,则需要使用 .find({}, {fields: ...})
。
对于具有多个用户的应用程序,发布所有用户并不是一个好主意,因此您可以只发布一个用户:
Meteor.publish("userById", function (requestedUserId) {
return Meteor.users.find({_id: requestedUserId}, {fields: ...});
});
然后在路由器中订阅时,传入用户id:
Meteor.subscribe("userById", this.params._id);
关于javascript - 发布用户数据,用于个人资料页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31458475/