gpt4 book ai didi

javascript - Meteor:需要有关 json 对象的解释

转载 作者:行者123 更新时间:2023-12-03 10:17:52 25 4
gpt4 key购买 nike

我正在尝试从模板中工作的助手中创建变量。我正在使用 API:

//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"
}
]

如果我正在使用这个(在客户端助手上):console.log(results.data) 并且我在控制台中看到一个具有正确字段的对象,但是:

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”变量在控制台中未定义。请解释我应该做什么才能使其正常工作。

最佳答案

您不能使用 helper 来显示 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');
}
});

关于javascript - Meteor:需要有关 json 对象的解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29779952/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com