我对nodejs和meteor很新。我需要创建一个页面content-type
application/json
和来自mongo集合的数据。所以当收集数据改变时,json页面必须改变。
对于json页面我使用这个例子: https://stackoverflow.com/a/23666992/1446182
if (Meteor.isServer) {
Meteor.startup(function () {
try{
var interval = Meteor.setInterval(function() {
var result = Meteor.http.call("GET", "http://192.168.2.144//ihale/meteorGetPage" );
var resultJson = JSON.parse(result.content);
var json = IhaleCollection.findOne();
IhaleCollection.update(json, {$set: {json: resultJson}});
}, 1000);
}
catch(err) {
console.log(err);
}
});
Router.map(function() {
this.route('jsonExample', {
where: 'server',
path: '/json',
action: function() {
var obj = IhaleCollection.findOne();
var headers = {'Content-type': 'application/json'};
this.response.writeHead(200, headers);
this.response.end(JSON.stringify(obj));
}
});
});
}
当Meteor.startup
我每秒开始更新IhaleCollection
时。
那么我如何在IhaleCollection
更改时更新json页面?
答案 0 :(得分:1)
你不能。反正不是这样的。 JSON没有内置机制来检测源是否已更改,并且假设路由器端点正在输出没有javascript的原始JSON数据,则不会发生自动更新。只有当客户端刷新端点时才会有更新。
Meteor通过在底层html页面中插入javascript来处理被动数据。如果你想利用它,那么你必须编写一个模板,编写一个帮助方法来返回JSON并在正文中使用helper方法。
辅助方法应如下所示:
Template.jsondoc.helpers{(
json: function(){
return JSON.stringify(IhaleCollection.findOne());
}
})
模板可以简单:
<template name="jsondoc">
{{json}}
</template>
,您的路线将如此简单:
Router.route('/jsondoc');