Villemh
Villemh

Reputation: 197

Meteor how to Get Variable Value from Server to Client?

Hei,

Im stuck for some reason. Im playing around with Arduino board and I want to read the data in the client.

My server code is this:

if(Meteor.isServer) {

  var five = Meteor.npmRequire("johnny-five");
  var board = new five.Board();

  Meteor.startup(function() {
      board.on("ready", Meteor.bindEnvironment(function() {
        var temperature = new five.Thermometer({
          controller: 'TMP36',
          pin: 'A0'
        });

        Meteor.setInterval(function() {
          console.log(temperature.celsius);
        }, 5000);
    }))
  })

}

I don't want to save the data to collection but to read it online. How do I pass the variable temperature.celsius from server to the client? I cannot run the code in the client since i'm using NPM require and it works only in the server.

Upvotes: 1

Views: 953

Answers (1)

Arnaud Weil
Arnaud Weil

Reputation: 2492

Right after the Meteor.setInterval definition, add this:

Meteor.methods({
  temperature: function () {
    return temperature;
  },
});

Then add, at the bottom of your code:

if (Meteor.isClient) { 
  Template.tempReport.result = function () {
    return Session.get('temperature') || ""; 
  }; 
  Template.tempReport.events = { 
    'click button' : function () { 
        Meteor.call('temperature',function(err, response) { 
            Session.set('temperature', response); 
        }); 
     } 
  }; 
}

And finally in your HTML:

<template name="tempReport">
  <div>Temperature: {{temperature}} <button>Update</button></div>
</Template>

Upvotes: 3

Related Questions