如何让 Meteor.Call 返回模板的值? [英] How to get Meteor.Call to return value for template?

查看:26
本文介绍了如何让 Meteor.Call 返回模板的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试过 要理解这篇关于这个概念的帖子,但是,我没能理解.我有以下简单的设置:

I've tried to understand this post regarding this concept, however, I'm failing to get it. I have the following simple setup:

/server/test.js
Meteor.methods({ 
  abc: function() {
    var result = {};
    result.foo = "Hello ";
    result.bar = "World!";
    return result;
  }
});

/client/myapp.js
var q = Meteor.call('abc');
console.log(q);

这个结构体返回到控制台undefined.

This structure returns to the console undefined.

如果我将 myapp.js 文件更改为:

If I change the myapp.js file to:

Meteor.call('abc', function(err, data) {
  !err ? console.log(data) : console.log(err);
}

我在控制台中收到了 Object.

I receive the Object in my console.

理想情况下,这是我想要做的,但它不起作用,在控制台中声明:无法读取未定义的属性问候"

Ideally this is what I'd like to be able to do, but it doesn't work, stating in the console: Cannot read property 'greeting' of undefined

/client/myapp.js
var q = Meteor.call('abc');

Template.hello.greeting = function() {
   return q.foo;
}

将数据从服务器对象传递到模板的任何帮助将不胜感激.我还在学习 JavaScript &流星.

Any help in passing the data from the server object into the template would be greatly appreciated. I'm still learning JavaScript & Meteor.

谢谢!

推荐答案

来自 Meteor.call 文档:

From the Meteor.call documentation:

在客户端,如果不传递回调并且不在存根内部,则调用将返回未定义,并且您将无法获取方法的返回值.那是因为客户端没有纤程,所以实际上没有任何方法可以阻止方法的远程执行.

On the client, if you do not pass a callback and you are not inside a stub, call will return undefined, and you will have no way to get the return value of the method. That is because the client doesn't have fibers, so there is not actually any way it can block on the remote execution of a method.

所以,你会想要这样做:

So, you'll want to do it like this:

Meteor.call('abc', function(err, data) {
  if (err)
    console.log(err);

  Session.set('q', data);
});

Template.hello.greeting = function() {
  return Session.get('q').foo;
};

一旦数据可用,这将被动地更新模板.

This will reactively update the template once the data is available.

这篇关于如何让 Meteor.Call 返回模板的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆