如何使 Meteor.user 场反应

how to make Meteor.user field reactive

我试图阻止打开多个浏览器的用户登录。

当用户注册时,我有一个 Meteor.user() 对象填充如下:

{
    "_id" : "uSS2RqZnnFwui67wk",
    "createdAt" : ISODate("2017-05-15T07:28:10.546Z"),
    "services" : {
        "password" : {
            "bcrypt" : "a$DPgA59Gmob4ajzjYZyh5auoHRUyQuF1/7M0KaWz.nzW0mIEqzlDK6"
        },
        "resume" : {
            "loginTokens" : [ 
                {
                    "when" : ISODate("2017-05-15T13:42:29.322Z"),
                    "hashedToken" : "tkoQnweSQhgRKGzaJTAkUU3/Ljd3p4wrBJfrRvRRlcY="
                }
            ]
        }
    },
    "username" : "johndoe",
    "emails" : [ 
        {
            "address" : "lkj@gmail.com",
            "verified" : false
        }
    ],
    "profile" : {
        "name" : "John Doe",
        "mobile" : "9637637941",
        "email" : "lkj@gmail.com",
        "address" : "kfasd, asdas,d as dsad",
        "gender" : "M",
        "state" : "Uttar Pradesh",
        "customerType" : "CLIENT",
        "isBlocked" : true
    },
    "status" : {
        "online" : true,
        "lastLogin" : {
            "date" : ISODate("2017-05-15T14:12:02.094Z"),
            "ipAddr" : "127.0.0.1",
            "userAgent" : "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0"
        },
        "idle" : false
    }
}

参考上面的代码,我正在尝试根据 user.profile.isBlocked* 状态更新 UI。

我的UI.html如下:

<template name="App_watch">
    {{#if isBlocked}}
      User Has been Blocked.
    {{else}}
      User has Access.
    {{/if}}
</template>

我的UI.js如下:

import { Meteor } from 'meteor/meteor';
import './UI.html';

Template.App_watch.helpers({
  isBlocked() {
    user = Meteor.users.find({_id: Meteor.userId});
    return user.profile.isBlocked;
  }
});

在下面的代码中,我只是监视是否有超过 1 个浏览器以相同的登录打开。如果是,则阻止用户,否则取消阻止用户。

import './fixtures.js';
import './register-api.js';

UserStatus.events.on("connectionLogin", function(fields) {
  var count = UserStatus.connections.find({userId : fields.userId}).count();
  if(count > 1) { //Block
    Meteor.users.update({_id: Meteor.userId()}, {$set: {"profile.isBlocked": true}});
  } else { // Unblock
    Meteor.users.update({_id: Meteor.userId()}, {$set: {"profile.isBlocked": false}});
  }
});

问题陈述:

我想让 isBlocked 变量在 isBlocked 标志为用户更改时响应。目前它是静态的,需要刷新。

尝试:

Template.App_watch.helpers({
  isBlocked() {
    return Meteor.user() && Meteor.user().profile && Meteor.user().profile.isBlocked;
  }
});

如果您要查找单个对象,则需要使用 .findOne() 而不是 .find(),因为后者 returns 是游标。它也是 Meteor.userId() 而不是 Meteor.userId