在加载任何其他内容之前,如何从我的设置集合中检索数据?

时间:2016-07-27 23:44:10

标签: mongodb meteor

我有一个名为Settings的mongo集合。它存储一些设置,如API密钥。这些设置应该可以在应用程序中调整,而无需访问服务器。

这些设置需要加载并在客户端之前出现。因为在API密钥的情况下,如果在API开始加载之前未定义密钥,API将崩溃。

我不能使用settings.json,因为据我所知,你不能在运行时更改它们。 Settings.json只能在服务器上进行硬编码吗?

2 个答案:

答案 0 :(得分:1)

使用回调使代码同步。

尝试以下内容,这可以解决您的问题: -

Meteor.methods({
'getApiKey': function () {
    return Settings.findOne().key //there is only one entry so far
 } });

//
function setKey(callback)
{
   Meteor.call('getApiKey', function (err, result) {
   if (err) console.log(err);

      Session.set('key', result);
      callback(err);
   });
}

//Wait for the `getApiKey` to complete, use callback.
setKey(function(err)
{
     var apiKey = Session.get('key'); //Set the key in the callback function
})

编辑: -

请尝试以下方法: -

Meteor.methods({
'getApiKey': function () {
    return Settings.findOne().key //there is only one entry so far
 } });

  var apiKey;
   Meteor.call('getApiKey', function (err, result) {
   if (err) console.log(err);

      Session.set('key', result);
      apiKey = Session.get('key'); 
      console.log(apiKey);
   });

让我知道它是否有效。

答案 1 :(得分:0)

这里有一个概念误解。简单的解决方案是检查api密钥是否已加载,然后运行相关代码。这样,应用程序就不会崩溃。

相关问题