0

我已经为我正在开发的应用程序构建了一个用户个人资料页面,当用户登录时该页面工作正常,但当没有人登录时,模板为空。我的目标是任何人(即使它没有在应用程序中注册)都能够看到用户配置文件。

这是代码:

出版物:

Meteor.publish('singleUser', function(userId) {
    if (this.userId) {
        var findById = Meteor.users.find(userId);
        return findById.count() ? findById : 'undefined';
    }
    return [];
 });

路由器:

this.route('user_profile', {
    path: '/users/:_id',
    waitOn: function() {
        return Meteor.subscribe('singleUser', this.params._id);
    },
    data: function() { 
        return Meteor.users.findOne({_id: this.params._id}); 
    }
});

个人资料模板:

<template name="user_profile">
    <h4>Username</h4>
    <p>{{username}}</p>
    <h4>User since:</h4>
    <p>{{createdAtFormatted}}</p>                   
</template> 

个人资料助手:

Template.user_profile.helpers({
    createdAtFormatted: function(){
        return  moment(this.createdAt).fromNow();
    }   
});

我不知道我的代码中缺少什么。

谢谢!

4

2 回答 2

3

你几乎明白了——你只需要修复发布功能。您在导航到个人资料页面时仅发布必要用户的方法是正确的。

在发布函数内部,this.userId指的是调用用户的 id。由于未登录的客户端没有userId,因此您的发布功能将返回[]并且客户端将无法呈现个人资料页面是理所当然的。发布函数的其余部分是不必要的——它应该返回一个游标,而不必处理所有找不到数据的可能性。我想你想要这样的东西:

Meteor.publish('userForProfilePage', function(userId) {
  check(userId, String);
  return Meteor.users.find(userId, {
    fields: {createdAt: 1, username: 1}
  });
});

请注意以下事项:

  • 我为函数使用了一个明确的名称来清楚地识别我在做什么。我发现userForProfilePage比 更清楚singleUser,但这是一个品味问题。请务必根据需要更改您的订阅。
  • 我对输入进行了简单的检查。userId这验证它是一个字符串而不是未定义的。您可以根据需要添加更复杂的检查。
  • 只有当检查通过时,我们才会为userId. 光标返回的文档将只包含_idcreatedAtusername字段(这是为了安全起见)。
于 2013-12-23T00:28:45.693 回答
1

我不太确定,您是想显示所有用户的个人资料还是只显示一个用户的个人资料,因为如果您退出,系统将不知道它当前正在与哪个用户交谈。我假设这是因为您说您想“查看用户配置文件”。

尝试这个:

Meteor.publish('allUsers', function() {
    return Meteor.users.find();
});

你也可以使用Meteor.methods().

Meteor.methods({
    allUsers: function () {
        return Meteor.users.find();
    }
});

并且不要忘记将您的模板包装成一个{{#each allUsers}}{{/each}}块。

编辑:关于安全问题,在将值传递给客户端之前对其进行映射。

Meteor.methods({
    allUsers: function () {
        return Meteor.users.find().fetch().map(function(user) {
            return {
                "name": user.username,
                "createdAt": user.createdAt
            };
        });
    }
});
于 2013-12-22T22:45:32.210 回答