【问题标题】:Meteor: how use data from an Http call in templatesMeteor:如何在模板中使用来自 Http 调用的数据
【发布时间】:2023-04-05 18:46:01
【问题描述】:

我在 Http main.js 中进行调用,这会将我返回到我的控制台“未捕获的类型错误:无法读取属性‘set’ of null” 无法从函数本身外部的 http 调用中检索信息。 谢谢你的帮助。

Template.prod.onCreated(function prodOnCreated() {
var tmpl = this;
tmpl.data = new ReactiveVar;

HTTP.call( 'GET', 'https://localhost:9002/rest/v2/electronics/products/search/?query=:price-asc:category:575', {}, function( error, response ) {
if ( error )
console.log( error );
 else {
console.log( response.data.products[0].code); // that works: display  "2140285"
tmpl.data.set(response.data);// Doesn't work: message in the console "Uncaught TypeError: Cannot read property 'set' of null"
}
});
});


Template.prod.helpers({
data: function() {
console.log('Hi you are in the data function');
return  Template.instance().data.get();
}
});

控制台显示:

main.js:40 Uncaught TypeError: Cannot read property 'set' of null(匿名函数)@main.js:40(匿名函数)@ httpcall_client.js:83(匿名函数)@ underscore.js?hash=8de51f9…:784xhr.onreadystatechange @ httpcall_client.js:172

【问题讨论】:

  • tmpl.data = new ReactiveVar(); 见括号
  • 嗨@Sasikanth 我纠正了它,我有同样的错误

标签: javascript http meteor xmlhttprequest


【解决方案1】:

首先你需要使用下面添加一个包

meteor add reactive-var

然后你可以像这样初始化 reactivevar

tmpl.data = new ReactiveVar();

【讨论】:

  • 这个包已经包含在meteor 1.3版本中:在JS的头部:import {} ReactiveVar from 'meteor / reactive-var';
  • 应该是import { ReactiveVar } from 'meteor / reactive-var'吧?
  • 实际上响应式变量有效,例如: Template.hello.onCreated(function helloOnCreated() { // 计数器从 0 开始 this.counter = new ReactiveVar(5); console.log(this. counter.get()); // 有效:显示 5 });
  • 带有复制功能的小型 repo 可能会有所帮助
猜你喜欢
  • 2016-05-16
  • 2016-10-22
  • 1970-01-01
  • 2015-07-13
  • 2013-06-15
  • 2017-06-20
  • 1970-01-01
  • 2015-06-30
  • 2014-10-10
相关资源
最近更新 更多