2016-06-11 148 views
-1

HTTP API请求填入HTML表我有一个表与流星

<table> 
<thead> 
    <tr> 
    <th>Year</th> 
    <th>Value</th> 
    </tr> 
</thead> 
<tbody> 
    <tr> 
    <td>1990</td> 
    <td>-</td> 
    </tr> 
    ... 
</tbody> 
</table> 

,我想打一个GET请求世界银行API在此表中填写的值。

我的GET请求是流星方法

Meteor.methods({ 
    getData: function() { 
    try { 
     const url = 'http://api.worldbank.org/countries/br/indicators/NY.GDP.MKTP.CD?date=1990:2000&format=json'; 
     const request = HTTP.get(url); 
     return request; 
    } catch (e) { 
     console.log(e); 
     return false; 
    } 
    }, 
}); 

,我打电话给我的方法从客户端

Meteor.call('getData', function(error, result) { 
    console.log(result); 
}); 

所以我在控制台中的值,但我想更换-在正确的值的HTML表格。

回答

0

您可以使用{{#each}}块帮助程序遍历数组。例如。

<tbody> 
{{#each getData}} 
<tr> 
    <td>{{date}}</td> 
    <td>{{value}}</td> 
</tr> 
{{/each}} 
</tbody> 

其中getData是提取数据的模板助手。但是,由于您获得的数据是异步的,因此您不能直接在助手中直接执行Meteor.call()

解决此问题的一种方法是使用会话变量('meteor add session'来安装软件包)。

首先,你要创建模板时获取数据并将其设置为会话变量:

Template.your_template.onCreated(function() { 
    Meteor.call('getData', function(error, result) { 
     // result.data[1] is the array of objects with the data 
     Session.set('bankData', result.data[1]); 
    }); 
}); 

然后,使用模板助手将数据传递到模板:

Template.your_template.helpers({ 
    getData: function(){   
     return Session.get('bankData'); 
    } 
});