HTTP.get不及时提供数据

时间:2016-02-26 23:09:43

标签: javascript meteor request

我正在尝试在ipinfo.io的帮助下显示用户位置。我创建了一个流星服务器方法:

 ipLocate: function() {
      HTTP.get("http://ipinfo.io", function(error, result) {
        var place = JSON.parse(result.content);
        city = place.city;
        state = place.region;
      });
        return [city,state];
    }

返回用户的城市和州(但仅在第二次执行时)。

我做了一个全球帮手

Template.registerHelper('locationFull', function() {

      // if (!Meteor.userId()) {

      Meteor.call('ipLocate', function(error, result) {
        response = result
        Session.set('location', response);
      })
      return Session.get('location');
}

目前没有显示任何内容。

如果我在客户端中手动运行HTTP.get请求(来自我的ipLocate方法),它将返回城市和州,但仅在我运行两次之后。

如何在页面加载时让我的全局帮助程序返回城市和州。

2 个答案:

答案 0 :(得分:1)

这是因为您异步运行请求。由于您的返回代码超出了HTTP.get回调(并且它需要,否则会抛出错误),因此没有值。它第二次返回值的原因是因为您将city和state声明为全局变量(在它们前面没有var限定符)。正确的方法是将您获得的数据存储在发布到客户端模板的Mongo集合中。如果您不知道如何存储和发布数据,请查看Meteor Guide

答案 1 :(得分:0)

我最终将我的HTTP调用放在Template.onCreated()中,并在全局帮助器中返回带有Session var的变量集。

喜欢:

 Template.registerHelper('locationFull', function() {
    return Session.get('locate');
  });

这很有用。