发布和订阅无法正常工作

Publish and Subscribe do not work correctly

发布和订阅无效。请在下面找到解决方案作为答案。

初始问题: 我正在尝试发布 facebook first_name,它在使用 Meteor 中的帐户 facebook 包登录时自动检索(存储在 services.facebook 下的用户集合中)。我已经删除了自动发布和不安全。

到目前为止我尝试过的是这样的:

服务器端

Meteor.publish("facebook_name", function() {
return Meteor.users.find({_id: this.userId}, 
  {fields: {'services.facebook.first_name' : true} });
});

客户端

Meteor.subscribe('facebook_name');

我在我的模板中使用的是这个

<div class="Name"><p>{{currentUser.services.facebook.first_name}}</p></div>

在删除自动发布之前,模板中显示的名称。

当用户通过 facebook oauth API 登录并使用 meteor accounts-facebook 实现身份验证时,所有需要的数据都存储在当前用户对象中 ( Meteor.user() )。

因此,您的用户架构类似于:

{
  "_id": "Ap85ac4r6Xe3paeAh",
  "createdAt": "2015-12-10T22:29:46.854Z",
  "services": {
  "facebook": {
    "accessToken": "XXX",
    "expiresAt": 1454970581716,
    "id": "XXX",
    "email": "ada@lovelace.com",
    "name": "Ada Lovelace",
    "first_name": "Ada",
    "last_name": "Lovelace",
    "link": "https://www.facebook.com/app_scoped_user_id/XXX/",
    "gender": "female",
    "locale": "en_US",
    "age_range": {
      "min": 21
    }
  },
"resume": {
  "loginTokens": [
    {
      "when": "2015-12-10T22:29:46.858Z",
      "hashedToken": "XXX"
    }
  ]
 }
},
"profile": {
  "name": "Sashko Stubailo"
 }
}

因此,如果您想检索用户的名称,您需要做的就是将当前用户发布到客户端,然后从用户对象中获取用户名。

// server
Meteor.publish("userData", function () {
  return Meteor.users.find({_id: this.userId});
});

// client
Meteor.subscribe("userData");

Template.templateName.helpers({
 // this function returns username
 Username : function(){
 // if user is logged in using facebook; otherwise user is logged in using password
 if   (Meteor.user().profile.name)
   return Meteor.user().profile.name;
 else 
   return Meteor.user().username;
}

现在您可以在视图中显示用户名:{{Username}}

这里是more info...

找到了我的问题的解决方案:

在 client/main.js 中设置流星项目时,如果您正在使用路由和模板而不是 main.html 模板,它将显示 import './main.html'; 这将阻止发布和订阅才能正常工作。