JDRussia
JDRussia

Reputation: 65

Get data from anonymous HTTP.call()

I'm curious, if it is possible to retrieve data from anonymous call of HTTP.call() function and place that data into template. So far I have following code in JS:

Template.weather.onCreated( function() {
   this.data = new ReactiveVar(0);
});
Template.weather.helpers({
    data: function () {     
       return Template.instance().data.get();
    },
    get_data: function() {
       HTTP.call('GET', 'http://path.to.server', {}, function(error, result) {
          if (error)
             console.log(error);
          else {
             console.log(result.data); // data is received 
             var tmp = result.data.main); //
             return tmp;
          }
       });
    }
});
Template.weather.events({
    'click': function(event, template) {
       console.log("click");
       template.data.set(Template.instance().data.get());
    }
});

and template:

<template name="weather">
<div class="container marketing">
    <hr class="featurette-divider">
    <div class="row featurette">
        <div class="col-md-7">
            <h2 class="featurette-heading">Weather</h2>
            <p style="background-color:#ccc">{{data}}</p>           
        </div>
    </div>                      
</div>

But I still struggling with placing the data in template. If anyone have any ideas, please share with me. Thanks in advance!

Upvotes: 0

Views: 83

Answers (1)

datacarl
datacarl

Reputation: 2771

Are you only loading the data once? If so you probably want to put your HTTP call in the onCreated callback.

Also, your return statement in the callback of your HTTP call is not assigned to anything so you will never see the result. You probably want to assign it to your templates data property?

Something like this should solve both issues for you.

Template.weather.onCreated( function() {
    var tmpl = this;
    tmpl.data = new ReactiveVar;
    HTTP.call('GET', 'http://path.to.server', {}, function(error, result) {
      if (error)
         console.log(error);
      else
         tmpl.data.set(result.data);

   });
});

Template.weather.helpers({
  data: function () {     
    return Template.instance().data.get();
  }
});

I hope that helps. I'm not quite sure if I understood your problem correctly, e.g. I don't know what you are trying to achieve with your event handler, but the above might set you off in the right direction if nothing else.

Upvotes: 1

Related Questions