我正在编写一个应用程序,根据收集计数显示估计的等待时间。我遇到的问题是当页面加载或刷新时,waitTime显示,但它首先显示0,大约一秒后,它会根据计数显示实际的waitTime。我假设这与从集合中获取计数的延迟变量有关,所以它显示初始计数为0然后得到实际计数并显示waitTime?
有没有办法让它只显示加载或刷新时的确切等待时间?
JS:
Template.home.helpers({
waitTime: function() {
var totalCount = Students.find().count();
var hour = totalCount/4;
if(totalCount < 4){
return 15*totalCount + " minutes"
}else if(totalCount >= 4 && totalCount%4 == 0){
return hour + " hour(s)";
}else if(totalCount >= 4 && totalCount%4 == 1){
hour = hour - .25;
return hour + " hour(s)" + " 15 minutes";
}else if(totalCount >= 4 && totalCount%4 == 2){
hour = hour - .5;
return hour + " hour(s)" + " 30 minutes";
}else if(totalCount >= 4 && totalCount%4 == 3){
hour = hour - .75;
return hour + " hour(s)" + " 45 minutes";
}
}
});
HTML:
<template name= "home">
<body>
<h2 id="insert">Approximate Wait Time: {{waitTime}}</h2>
<div class="col-lg-6 col-lg-offset-3">
<!-- Quick form from autoform package creates sign in form and populates collection with data-->
{{>quickForm id="studentForm" collection="Students" type="insert" template="bootstrap3-horizontal" label-class="col-sm-3" input-col-class="col-sm-9"}}
</div>
</body>
</template>
答案 0 :(得分:1)
最直接的方法是在数据准备好之前不渲染视图(或至少是视图的相关部分)。两种主要方式是等待订阅准备就绪,或者等到你拥有所需的数据值。
后者很难,因为根据我的判断,0是可能的值。所以我建议前者。
假设您的订阅与您的模板相关联,您可以等待订阅准备就绪:
<template name= "home">
<body>
{{#if Template.subscriptionsReady}}
<h2 id="insert">Approximate Wait Time: {{waitTime}}</h2>
<div class="col-lg-6 col-lg-offset-3">
<!-- Quick form from autoform package creates sign in form and populates collection with data-->
{{>quickForm id="studentForm" collection="Students" type="insert" template="bootstrap3-horizontal" label-class="col-sm-3" input-col-class="col-sm-9"}}
</div>
{{else}}
Loading...
{{/if}}
</body>
</template>
答案 1 :(得分:0)
var totalCount = Students.find().count();
第一次加载页面时,meteor的反应性尚未确定,因此计数始终为0,使显示屏显示0.您需要检查订阅是否已完成,然后显示页面
Template.home.created = function() {
this.loading = new ReactiveVar(true)
let subHandler = Meteor.subscribe('your-publication-name')
this.loading.set(!subHandler.ready())
}
然后在你的模板帮助器中,检查loading
是否为true,返回加载文本或sth,否则返回结果
像这样的东西
waitTime: function() {
if (Template.instance().loading.get()) return "Loading";
// the rest of the code
}