使用javascript的无限循环(Angular NgFor和http请求)
Infinite loop with javascript (Angular NgFor and http request)
问题是,在我试图检查资源服务器上是否存在一个映像的同时,Angular NgFor正在执行其工作。
我可以猜测,img.src执行了请求,然后我在回调中的返回没有按预期返回,事实上,defaultPrincipalUrl方法没有按预期任何返回,因此Angular一次又一次地执行相同的请求。
但是,我不知道用Javascript解决这个问题的方法。
html中的NgFor看起来是这样的。
<div class="formItem">
<div *ng-for="#principal of localService.defaultPrincipals">
<img src="{{defaultPrincipalUrl(principal)}}" />
</div>
</div>
其中localService.defaultPrincipals是一个包含映像名称的数组。
在Angular2@Component类中,我有下一个实现。
private imageExists(imageSrc, callback) {
var img = new Image();
img.onload = function () { callback(imageSrc, true); };
img.onerror = function () { callback(imageSrc, false); };
img.src = imageSrc;
}
defaultPrincipalUrl(principal) {
var im = IMAGE_DOMAIN + '/principal/' + principal;
console.log(im);
this.imageExists(im, function (imageSrc, exists) {
console.log('RESULT: url=' + imageSrc + ', exists=' + exists);
if (exists) {
return imageSrc;
} else {
return '#';
}
});
}
使用异步管道。
<div class="formItem">
<div *ng-for="#principal of localService.defaultPrincipals">
<img src="{{defaultPrincipalUrl(principal) | async}}" />
</div>
</div>
defaultPrincipalUrl的结果必须是promise,因为回调是异步的:
private imageExists(imageSrc, callback) {
var img = new Image();
img.onload = function () { callback(imageSrc, true); };
img.onerror = function () { callback(imageSrc, false); };
img.src = imageSrc;
}
defaultPrincipalUrl(principal) {
var im = IMAGE_DOMAIN + '/principal/' + principal;
console.log(im);
let self_ = this;
return new Promise(function(resolve, reject) {
self_.imageExists(im, function (imageSrc, exists) {
console.log('RESULT: url=' + imageSrc + ', exists=' + exists);
if (exists) {
resolve(imageSrc);
} else {
resolve('#');
}
});
});
}
相关文章:
- Meteor如何接收HTTP请求
- 在我的情况下,如何进行http请求
- 使用插件收听Firefox标签的http请求
- http请求使用html而不是json进行响应
- 在node-js路由中发出http请求
- 是否可以在没有HTTP请求或<输入>
- Acync JS HTTP请求通知请求
- PhantomJs在控制台中发出http请求时不会返回任何状态
- PHP处理来自一个页面的http请求,并将其显示在另一个页面上
- Firefox插件-如何发出http请求
- 验收测试主要针对传出的http请求
- 验证HTTP请求来自NFC标签上的点击
- 如何制作'http请求'在Node js中同步
- 为什么我在Cloud9中的http请求总是返回错误
- AngularJS Typeahead和$http请求限制
- HTTP请求使用cURL,但在浏览器中使用javascript时会得到CORS响应
- 如何使用Chrome扩展API获取网页的所有HTTP请求
- 将http请求中的数据传递给C#控制器
- 在初始化路由之前发送$http请求
- 从客户端捕获 HTTP 请求(包括 ajax)