Meteor HTTP 调用不断加载图像
Meteor HTTP call loads image constantly
在我的 Meteor 应用程序中,我试图从这个 API 加载随机图像,我得到一个 JSON 像:
{
"id":2026
"url": "https:// ... " ,
"large_url":null,
"source_id":609,
"copyright":"CC0",
"site":"unsplash"
}
我是这样做的:
if (Meteor.isClient) {
Template.body.helpers({
randomImage: function() {
Meteor.call("unImage", function(error, results) {
Session.set('url', results.data.url);
});
return Session.get('url');
}
});
}
if (Meteor.isServer) {
Meteor.methods({
unImage: function() {
this.unblock();
return Meteor.http.call("GET", "http://www.splashbase.co/api/v1/images/random");
}
});
}
在我的 html:
<div class="header" style="background-image: url('{{randomImage}}')">
...
</div>
这是有效的,但它每秒 重新加载 图像 - 或多或少。我猜这是因为服务器端的函数 unImage
与服务器或类似的东西一起加载(不确定);无论如何我不能让它停下来。关于如何解决它的任何想法?为什么会这样?
这是因为 randomImage
助手中的会话变量。
Session variables 本质上是反应性的,只要它的值发生变化,它就会重新 运行 在一个块中。
在这种情况下,帮助程序代码被一次又一次地重新运行,因此,Meteor 方法被一次又一次地调用
因此,将助手中的 Meteor.call
移动到呈现的事件,如下所示
if (Meteor.isClient) {
Template.body.rendered= function(){
Meteor.call("unImage", function(error, results) {
Session.set('url', results.data.url);
});
}
Template.body.helpers({
randomImage: function() {
return Session.get('url');
}
});
}
一旦模板准备就绪并设置 url
变量,应该调用 Meteor 方法,因此反应性帮助程序 randomImage
获得 re-运行 并获得 same
的值
在我的 Meteor 应用程序中,我试图从这个 API 加载随机图像,我得到一个 JSON 像:
{
"id":2026
"url": "https:// ... " ,
"large_url":null,
"source_id":609,
"copyright":"CC0",
"site":"unsplash"
}
我是这样做的:
if (Meteor.isClient) {
Template.body.helpers({
randomImage: function() {
Meteor.call("unImage", function(error, results) {
Session.set('url', results.data.url);
});
return Session.get('url');
}
});
}
if (Meteor.isServer) {
Meteor.methods({
unImage: function() {
this.unblock();
return Meteor.http.call("GET", "http://www.splashbase.co/api/v1/images/random");
}
});
}
在我的 html:
<div class="header" style="background-image: url('{{randomImage}}')">
...
</div>
这是有效的,但它每秒 重新加载 图像 - 或多或少。我猜这是因为服务器端的函数 unImage
与服务器或类似的东西一起加载(不确定);无论如何我不能让它停下来。关于如何解决它的任何想法?为什么会这样?
这是因为 randomImage
助手中的会话变量。
Session variables 本质上是反应性的,只要它的值发生变化,它就会重新 运行 在一个块中。
在这种情况下,帮助程序代码被一次又一次地重新运行,因此,Meteor 方法被一次又一次地调用
因此,将助手中的 Meteor.call
移动到呈现的事件,如下所示
if (Meteor.isClient) {
Template.body.rendered= function(){
Meteor.call("unImage", function(error, results) {
Session.set('url', results.data.url);
});
}
Template.body.helpers({
randomImage: function() {
return Session.get('url');
}
});
}
一旦模板准备就绪并设置 url
变量,应该调用 Meteor 方法,因此反应性帮助程序 randomImage
获得 re-运行 并获得 same