0

我正在编写一个应用程序,它根据集合的计数显示估计的等待时间。我遇到的问题是,当页面加载或刷新时,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>
4

2 回答 2

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>
于 2017-04-20T04:35:01.580 回答
0
var totalCount = Students.find().count();

第一次加载页面时,meteor的reactivity还没有建立,所以count一直为0,显示显示为0。需要查看是否订阅已经完成,然后显示页面

Template.home.created = function() {
  this.loading = new ReactiveVar(true) 
  let subHandler = Meteor.subscribe('your-publication-name')
  this.loading.set(!subHandler.ready())
}

然后在您的模板助手中,检查是否loading为真,返回加载文本或某事,否则返回结果

像这样的东西

waitTime: function() {
  if (Template.instance().loading.get()) return "Loading";

  // the rest of the code
}
于 2017-04-20T04:33:12.710 回答