meteor - 更改配置文件字段时如何等待 Meteor.users

标签 meteor subscriptions

我在 Meteor.users 系统定义的集合中使用 profile 字段来存储有关用户在每个通信 channel 上读取的最后一条消息的信息,结构如下:

profile : {
    lastMsgRead : [
        {channelId: 'YYEBNEI7894K', messageCreatedAt: '14578970667"}
        {channelId: 'GERYUE789774', messageCreatedAt: '14578999845"}
    ]
}

我发现读取 lastMsgRead 字段失败,因为在客户端上读取时数组仍然为空。
我通过以下方式正确地将此字段发布给客户端:
Meteor.publish(null, function() {
    return Meteor.users.find({}, {fields: {_id: 1, username: 1, emails: 1, profile :1}});

我从位于 lib 目录中的客户端库中读取它的值,方式如下:
var chHistory = Meteor.user().profile.lastMsgRead;

调试我的代码,看起来我对 profile 字段所做的更改在我阅读它们时尚未传播到所有客户端。所以我需要等待订阅 Meteor.users 准备好,但我没有它的句柄——你可以从框架中自动获得它。

如何等待 Meteor.users 订阅准备就绪?

最佳答案

因为meteor 没有为您提供当前用户订阅的句柄,所以没有明显的方法来等待数据。以下是一些选项:

使用 guard

处理这个问题的典型方法是添加 guards到您的代码。在遇到此问题的模板中,您可以编写如下内容:

var user = Meteor.user();
var lastMsgRead = user && user.profile && user.profile.lastMsgRead;

如果你发现你写了很多代码,你可以把它分解成一个共享函数:

var extractProfileValue = function(key) {
  var user = Meteor.user();
  return user && user.profile && user.profile[key];
};

并像这样使用它:

var lastMsgRead = extractProfileValue('lastMsgRead');

显示微调器

您可以测试模板本身中是否存在用户的个人资料:

<template name='myTemplate'>
  {{#unless currentUser.profile}}
    // show spinner or loading template here
  {{else}}
    // rest of template here
  {{/unles}}
</template>

如果您希望在所有页面上都有这种体验,您可以将其添加到您的布局模板中。

冗余发布者

警告:我没有试过这个

获取用户订阅句柄的一种方法是添加一个冗余发布者并订阅它:

Meteor.publish('myProfile', function() {
  return Meteor.users.find(this.userId, {fields: {profile: 1}});
});

然后在您的路由器中:

waitOn: function () {
  return Meteor.subscribe('myProfile');
}

关于meteor - 更改配置文件字段时如何等待 Meteor.users,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30285764/

相关文章:

google-cloud-platform - gcloud beta pubsub 订阅拉取格式

node.js - Meteor 中的线性执行模型是什么?

ios - 是否有一种简单的方法可以检查用户在 App Store 上的订阅状态,或者唯一的方法是进行收据和订阅验证?

meteor - Iron Router onBeforeAction 未被调用

meteor - 阻止meteor 下载包更新

java - youtube.subscriptions.list (api v3) - nextPageToken 不可用

ios - 获取 YouTube channel 订阅视频 JSON 列表

ios - 包月申请

javascript - 如何使用 bool 值查询 MongoDB 中的字段并返回 bool 值(true 或 false)

javascript - Meteor.user() 和 localStorage.getItem ('Meteor.userId' )返回 null