Search code examples
meteortypescriptangular2-meteor

publishing to user if he's logged in


I'm writing a meteor-angular2 project with the accounts-password package.

I'm trying to find out if the user is logged in and if he is, to publish the content.

this is my typescript code:

import {Meteor} from 'meteor/meteor';
import {RoomsCollection} from "../collections/rooms";

Meteor.publish('rooms',()=>{
    if (!this.userId) {
        return null;
    } else {
        return RoomsCollection.find();
    }
});

as you can see i'm using this.userId but it seems that this is undefined.

this is the error:

TypeError: Cannot read property 'userId' of undefined

I don't quite understand how an anonymous function can have this.userId, i'm actually reading the book 'You First Meteor Application' from 2014. so maybe they where breaking changes... or i'm missing something.

I'm new to Meteor so any information regarding the issue would be greatly appreciated.


Solution

  • In your code you have:

    ()=>{
        if (!this.userId) {
    

    Don't use an arrow function if you want this to be driven by the caller! Instead do:

    function() {
        if (!this.userId) {
    

    More

    https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html