【问题标题】:how to access an object from meteor.call如何从meteor.call访问对象
【发布时间】:2015-06-16 12:25:41
【问题描述】:

只是想在 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(result),它会显示在 javascript 控制台中并显示预期结果。但是,我无法让它填充 recordCnt。

有什么想法吗?

【问题讨论】:

    标签: templates object meteor callback server


    【解决方案1】:

    您无法按照自己的方式进行操作,因为来自 Meteor.call 的回调异步运行。

    但是,您可以使用回调设置 Session 值并让您的助手读取 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”方式的示例。

    【讨论】:

    • Template.showTotals.rcdCount = function() {} delcairng 这样的助手太老了
    • 这行得通。对于大型数据集,会话是否可以限制?如果我试图提取 500 条记录等会发生什么?
    • 考虑使用自定义出版物来实现这一点。 Meteor.publish 可以做的不仅仅是发布游标。查看here 以获得非常详细的示例。这可能是完成您在问题中尝试做的更好的方法。
    猜你喜欢
    • 2018-04-26
    • 1970-01-01
    • 2017-12-29
    • 2011-01-15
    • 2018-09-20
    • 1970-01-01
    • 2017-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多