【问题标题】:Accessing variables from HTTP.get从 HTTP.get 访问变量
【发布时间】:2015-07-30 07:44:57
【问题描述】:

我正在尝试访问 Meteor Accounts.onCreateUser 用户创建函数中名为 city 的变量,但我没有成功。我试图在 HTTP.get 调用结束时返回 city 并且还尝试在 HTTP.get 之外创建 city var 并在不使用 var 的情况下简单地设置 city 但这些事情似乎都没有奏效。当 console.log(city) 运行时,它会准确地输出所需的信息,因此这个变量一定不是问题。如果我犯了一个错误,请原谅我。

Accounts.onCreateUser( function (options, user) {

if (options.profile) {

  options.profile.picturelrg = "http://graph.facebook.com/" + user.services.facebook.id + "/picture/?type=large";
  user.profile = options.profile;
  options.profile.picturesm = "http://graph.facebook.com/" + user.services.facebook.id + "/picture/?type=small";
  options.profile.messenger = "https://www.messenger.com/t/" + user.services.facebook.id;


 HTTP.get("http://ipinfo.io", function (error, result) {
    var place = JSON.parse(result.content);
    var city = place.city;
    console.log(city);

  });


  options.profile.city = city;


}

  return user;

});

【问题讨论】:

  • HTTP.get() 是异步的,因此它会在脚本继续运行时单独执行。 city 在您尝试使用时还无法访问。您必须单独重构和设置值。试试Thinking Asynchronously (NodeCasts)
  • 感谢您的评论和回答。 “place”和“city”现在已成功保存到数据库。

标签: javascript meteor scope


【解决方案1】:

技术上正确的方法是您需要使用HTTP.get 的同步版本。有关示例,请参见 docsthis question

但是还有一个更根本的问题:您试图获取用户的位置数据,但 onCreateUser 仅在服务器上运行。所以即使你确实解决了这个问题,你最终会在每个用户的配置文件中得到相同的数据。您需要在客户端上运行get 并通过一种方法进行更新。试试这样的:

Accounts.createUser(options, function(err) {
  if (!err) {
    HTTP.get(..., function(err, result) {
      var city = ...;
      var place = ...;
      Meteor.call('updateProfileWithCityandPlace', city, place);
    });
  }
});

Meteor.methods({
  updateProfileWithCityandPlace: function(city, place) {
    check(city, String);
    check(place, String);

    Meteor.users.update(this.userId, {
      $set: {'profile.city': city, 'profile.place': place}
    });
  }
});

【讨论】:

    猜你喜欢
    • 2015-06-26
    • 1970-01-01
    • 2011-02-16
    • 2023-04-10
    • 2021-02-05
    • 1970-01-01
    • 2010-11-25
    • 2019-10-13
    • 2023-03-18
    相关资源
    最近更新 更多