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

- QUESTION -

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?

- ANSWER -

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 }
      }
    });
  }
});

0 comments:

Post a Comment

Powered by Blogger.