How to get Meteor.Call to return value for template?

后端 未结 4 1437
情歌与酒
情歌与酒 2020-12-02 12:11

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.method         


        
相关标签:
4条回答
  • 2020-12-02 12:55

    This happens because Npm.require has Async behavior. That's the reason that you have to write a callback for Meteor.call.

    But there is a solution, just use install(mrt add npm) and you'll get a function named Meteor.sync(//...) with this you can do both games: sync and async in your Meteor.call().

    Reference: http://www.sitepoint.com/create-a-meteor-app-using-npm-module/

    0 讨论(0)
  • 2020-12-02 13:02

    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.

    0 讨论(0)
  • 2020-12-02 13:04

    You can get the return value of a Meteor method for use in a template by using a reactive variable. Check out the working demonstration on Meteorpad

    0 讨论(0)
  • 2020-12-02 13:07

    I went for a ghetto solution. But, it works for me, which is what matters, to me. Below is my code, which, in concept, I think, solves OP's problem.

    In the client's main.js:

    Meteor.setInterval(function() {
        confirmLogin();
    
    }, 5000); 
    

    This runs the confirmLogin() function every five seconds.

    The confirmLogin function (in the client's main.js):

    function confirmLogin() {
        Meteor.call('loggedIn', function (error, result) {
            Session.set("loggedIn", result);
        });
    
    }
    

    The loggedIn method (in the server's main.js):

    loggedIn: function () {
        var toReturn = false;
        var userDetails = Meteor.user();
        if (typeof userDetails["services"] !== "undefined") {
            if (typeof userDetails["services"]["facebook"] != "undefined") {
                toReturn = true;
            }
        }
    
        return toReturn;
    },
    

    The relevant helper:

    loggedIn: function () {
        return Session.get("loggedIn");
    }
    
    0 讨论(0)
提交回复
热议问题