Search code examples
angularrxjsangular-meteor

Angular 2.0 Meteor: How to subscribe collection correctly?


I've introduced a publisher for a collection on the server side with the following code:

Meteor.publish('posts', () => Posts.find());

Now I want to subscribe to the collection on the client side. As an example I want to print the number of entries in the collection to the console, whenever the data has changed:

ngOnInit() { Meteor.subscribe('posts', () => { console.log(Posts.find().count()); }); }

The result is somehow confusing to me:

Observable {_isScalar: false, source: ObservableCursor, operator: CountOperator}

It seems I've misunderstood the whole concept. What is the right way to implement this functionallity?


Solution

  • I think you are missing some common code, which I usually put in /common

    model.js:

    // Collections that exist on the server database
    Posts = new Mongo.Collection("posts");
    

    The effect of this is to make 'Posts' a variable in both client and server code.

    Component code:

    Meteor.subscribe('posts', () => []);
    
    this.helpers({
      posts: () => Posts.find(),