2015-04-21 2 views
0

Я пытаюсь сделать переменную из помощника, работающего в шаблоне. Я использую API:Метеор: требуется объяснение о объектах json

//client 

Template.hello.helpers({ 
    fooVar: function(){ 
     return Meteor.call('checkApi', function(error, results) { 
      re = JSON.parse(results.content); //returns json(see json response) 
      console.log(re[0].foo); // returns right value 
      console.log(re); //returns json 
      return re[0].foo //not working 
     }); 
    } 
    }); 

сервер:

//server 
Meteor.methods({ 
    checkApi: function() { 
     this.unblock(); 
     return Meteor.http.call("GET", "https://someApi/getData",{ 
      headers: { 
       "Auth": "myToken" 
      } 
     }); 
    } 
    }); 

Мой шаблон:

... 
{{>hello}} 
<template name="hello"> 
{{fooVar}} //not working 
</template> 

JSON ответ:

[ 
    { 
    "FirstValue": "I'm the first value", 
    "SecondValue": "I'm the second value" 
    } 
] 

I'f я использую это (на клиентском помощнике): console.log(results.data) и я вижу объект в консоли с правой fieilds, но это:

console.log(results.data.FirstValue) is not working 

Это работает хорошо:

re = JSON.parse(results.content); //returns json(see json response) 
console.log(re[0].foo); // returns right value 

Но в шаблоне переменной «fooVar» не определено в консоли. Пожалуйста, объясните, что я должен сделать, чтобы это правильно работало.

ответ

1

Вы не можете использовать хелпер для отображения значения Meteor.call ('...'). Проверьте https://atmospherejs.com/simple/reactive-method или сделайте что-нибудь вроде

Template.hello.onCreated(function() { 
    Meteor.call('checkApi', function(error, results) { 
     re = JSON.parse(results.content); 

     Session.set('methodReturnValue', re[0].foo); 
    }); 
}); 

Template.hello.helpers({ 
    fooVar: function(){ 
     return Session.get('methodReturnValue'); 
    } 
}); 
+0

Спасибо, он работает. Но что мне делать с использованием объекта (из re.data) в моем шаблоне? – bartezr

+0

Хммм, похоже, что results.data - это массив, поэтому вам нужно перебирать его или получить первый объект, например results.data [0] .FirstValue – juliancwirko

Смежные вопросы