我已经完成了基本的排行榜应用并阅读了进一步的文档,最后决定使用本教程作为指南制作我自己的应用:http://meteorcapture.com/publishing-data-from-an-external-api/
我的当前代码似乎可以解决,直到将数据传递回客户端。我似乎无法从服务器获取数据。即使我订阅并发布所有设置。
我已经减少并简化了我的代码,但减少了错误点:
MyMp = new Mongo.Collection('mymp');
if (Meteor.isClient) {
Session.setDefault('searching', false);
Tracker.autorun(function(){
if(Session.get('postcode')){
var twfyHandle = Meteor.subscribe('twfySearch', Session.get('postcode'));
Session.set('searching', ! twfyHandle.ready());
}
});
Template.searchForm.events({
'submit form': function(event, template) {
event.preventDefault();
var postcode = template.$('input[type=text]').val();
if (postcode) {
Session.set('postcode', postcode);
}
}
});
Template.body.helpers({
mymp: function() {
return MyMp.find();
},
searching: function() {
return Session.get('searching');
}
});
}
if (Meteor.isServer) {
Meteor.publish('twfySearch', function(postcode){
console.log(postcode); // this received ok
var self = this;
var mp = {first_name: 'Test Name', party: 'Labour'}
self.added('mymp', Random.id(), mp);
self.ready();
});
}
我的HTML文件中的模板:
<body>
<h1>Get Details on your MP and Constituency</h1>
<h2>Enter your post code below</h2>
{{> searchForm }}
{{#if searching }}
<p>Searching...</p>
{{else}}
<div class="">
{{> twfyResults }}
</div>
{{/if}}
</body>
<template name="twfyResults">
{{ mp.first_name }}
</template>
<template name="searchForm">
<form>
<input type="text" name="postcode" id="postcode" />
<input type="submit" value="Search" />
</form>
</template>
我将邮政编码传递给服务器,服务器填充了一个基本的JSON对象&#39; mp&#39;在发布方法下并使其准备就绪()。
这是失败的地方。虽然我的console.log()调用显示服务器正在获取邮政编码并创建mp对象。客户没有得到任何回报!
更新: 我已设法在浏览器控制台MyMp.findOne()中手动运行,并返回服务器创建的对象。但是,我的模板似乎无法访问此对象。还有&#39; mp&#39;对象本身并不存在。
答案 0 :(得分:0)
我在代码中发现了三个错误。
通过更改twfyResults模板以引用辅助方法来解决此问题:
<template name="twfyResults">
{{ mymp.first_name }}
</template>
Template.body.helpers({
searching: function() {
console.log(this);
return Session.get('searching');
}
});
Template.twfyResults.helpers({
mymp: function() {
return MyMp.findOne();
}
});