2013-03-11 54 views
4

我一直在试图从Meteor.methods通话中访问this.userId变量调用的时候,但它似乎不工作时,我尝试通过调用该方法不工作Meteor.setTimeout或Meteor.setInterval。访问this.userId从内Meteor.SetTimeout

这是我的本钱:

if (Meteor.is_server) { 
    Meteor.methods({ 
     getAccessToken : function() { 
      try { 
       console.log(this.userId); 
       return Meteor.users.findOne({_id: this.userId}).services.facebook.accessToken; 
      } catch(e) { 
       return null; 
      } 
     } 
    }); 

    var fetch_feed = function() { 
     console.log(Meteor.call("getAccessToken")); 
     [...] // A bunch of other code 
    }; 

    Meteor.startup(function() { 
     Meteor.setInterval(fetch_feed, 60000); // fetch a facebook group feed every minute 
     Meteor.setTimeout(fetch_feed, 3000); // initially fetch the feed after 3 seconds 
    }); 
} 

看终端的日志中,this.userId总是返回空。但是,如果我尝试从客户端或通过控制台调用方法,它将返回正确的ID。

如何走到这一步不从Meteor.setInterval内工作?这是一个错误还是我做错了什么?

+0

“this.userId”指向“null”还是“getAccessToken”返回null,因为您捕获了异常并强制它? – Rahul 2013-03-11 15:26:52

+0

来自'getAccessToken'的错误是'TypeError:无法读取undefined'的属性'services',因为'this.userId'返回'null'。如果我从控制台调用该方法,它将起作用,但是从Meteor.setTimeout或Meteor.setInterval失败。 – 2013-03-11 16:20:57

+0

顺便说一句。如果我将setTimeout和setInterval移到客户端,这可以正常工作。就像this.userId在服务器端调用时不可用。但基于文档,它应该可以在任何地方使用:http://docs.meteor.com/#method_userId – 2013-03-11 21:31:27

回答

2

流星用户标识的与客户端连接相关联。服务器可以与许多客户端交互,并且方法内的this.userId将告诉你哪个客户端已经要求运行该方法。

如果服务器使用Meteor.call()运行的方法,那么它不会有用户标识,因为它没有任何客户端运行。

的方法使客户端调用服务器上运行的功能。对于服务器会触发自己的东西,javascript函数将会执行。

-1

我使用了一种解决方案 - 有时您不想让该方法成为函数,但确实希望它仍然是一种方法。在这种情况下,黑客攻击,使这项工作:

  var uniqueVar_D8kMWHtMMZJRCraiJ = Meteor.userId(); 
      Meteor.setTimeout(function() { 
        // hack to make Meteor.userId() work on next async 
        // call to current method 
        if(! Meteor._userId) Meteor._userId = Meteor.userId; 
        Meteor.userId = function() { 
         return Meteor._userId() || uniqueVar_D8kMWHtMMZJRCraiJ 
        }; 
        Meteor.apply(methodName, args); 
       } 
      , 100); 

一些简要说明:我们保存Meteor.userIdMeteor._userId,并与之前的任何的返回Meteor._userId()如果是真,否则的Meteor.userId()历史值的函数覆盖Meteor.userId这发生过。这个历史价值被保存在一个不可能发生两次var名称的地方,这样就不会发生上下文冲突。

+0

这是否会支持多个用户?在超时解决之前进行第二次流星呼叫时会发生什么?另外,如果var name中的随机字符每次都是相同的,那有什么意义呢?你只是整理范围? – 2015-10-22 15:57:20

+0

哇,不,不要这样做。这是一个很糟糕的事情,会导致很多问题。 user728291的回答是正确的 – JeffC 2017-02-27 06:45:04