如何从meteor.call访问对象

时间:2015-04-10 17:25:00

标签: templates object meteor callback server

试图在Meteor JS中解决问题。我试图将Meteor.call结果对象传回模板。这是我的代码:

HTML模板

<template name="showTotals">
    <div class="container">
        {{#each recordCnt}}
        {{/each}}
    </div>
</template>

客户端JS

//get a count per item
Template.showTotals.recordCnt = function(){

    Meteor.call('getCounts', function(err, result) {
    if (result) {
        //console.log(result); <-this shows object in javascript console
        return result;
        }
        else {
            console.log("blaaaa");
        }
    });

}

服务器JS

Meteor.startup(function () {

    Meteor.methods({

      getCounts: function() {
        var pipeline = [{$group: {_id: null, count: {$sum : 1}}}];
        count_results = MyCollection.aggregate(pipeline);
        return count_results;
      }
    });
  });

全球JS

MyCollection = new Meteor.Collection('folks'); 

我尝试为调用结果添加console.log(结果),并在javascript控制台中显示预期结果。但是我无法将其填充到recordCnt中。

有什么想法吗?

1 个答案:

答案 0 :(得分:-1)

你不能按照你想要的方式去做,因为来自Meteor.call的回调是异步运行的。

但是,您可以使用回调来设置会话值,并让帮助者改为Session.get()

Template.showTotals.rcdCount = function() {
  return Session.get('rcdCount');
}

Template.showTotals.rendered = function() {
  Meteor.call('getCounts', function(err, result) {
    if (result) {
        Session.set('rcdCount', result);
        }
        else {
            console.log("blaaaa");
        }
    });
}

请参阅here以获得类似的答案,其中包含一个“hacky”方式的示例。

相关问题