Meteor: data passed to template from Iron Router, is empty at first load

こ雲淡風輕ζ 提交于 2019-12-13 04:34:55

问题


I'm facing a strange problem. I'm using Iron Router controller to pass data to template:

Router.route('/wards/add/:_id?', {name: 'wards.add', controller: 'WardAddController'});

    WardAddController = RouteController.extend({
      action: function() {
        this.render('addWard', { 
          data: function(){
            return { hospitals : Hospitals.find({}), hospital_id : this.params._id }
          }
        });
      }
    });

I return a variable 'hospitals', that should contain all the collection data. Template:

<div class="jumbotron">
    {{#each hospitals}}
        {{name}}<br>
    {{/each}}
</div>

At first page load, if I type the directly the url of the page, there are no items. If I type Hospitals.find({}).fetch() (insecure is active) in the browser console, it return an empty object.

But if i change pages, navigating on the website a while, and return the the listing page, items appears.

Any idea?


回答1:


In the server folder, add publish.js and inside it add:

Meteor.publish('hospitals', function() {
  return Hospitals.find({});
});

Then try subscribing to hospitals from your controller:

WardAddController = RouteController.extend({
  action: function() {
    this.render('addWard', { 
      waitOn: function() {
        return [
              Meteor.subscribe('hospitals')
           ];
      },
      data: function(){
        return { hospitals : Hospitals.find({}), hospital_id : this.params._id }
      }
    });
  }
});


来源:https://stackoverflow.com/questions/30824800/meteor-data-passed-to-template-from-iron-router-is-empty-at-first-load

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!