Ajmal
Ajmal

Reputation: 107

Returning values from a subscription callback

I am trying to get the value of a field from a document returned via a subscription. The subscription is placed inside a helper function. I had a callback function within the subscription return this value and then I assigned the return value to a variable (see code). Finally, I had the helper return this value. However, the value returned is a subscription object (?) and I can't seem to get anything out of it.

Code:

Template.myTemplate.helpers({
    'returnUser':function(){
        var id = Session.get('currentUserId');
        var xyz = Meteor.subscribe('subscriptionName',id,function(){
            var user = accounts.find().fetch({_id: id})[0].username; 
            return user;
            }
        return xyz;
        }
});

Any help will be much appreciated. :)

Upvotes: 0

Views: 290

Answers (1)

alexhenkel
alexhenkel

Reputation: 602

You have to load first your subscriptions when the template is created, this creates an instance of your data with Minimongo.

Template.myTemplate.onCreated(function () {
    var self = this;
    self.autorun(function() {
        self.subscribe('subscriptionName',id);
    });
});

Then in the helper, you can make a query to retrieve your data

Template.myTemplate.helpers({
    'returnUser': function(){
        var id = Session.get('currentUserId');
        return accounts.findOne(id).username;
    }
});

Upvotes: 2

Related Questions