Problem is meanwhile I'm trying to check if one image exists on the resources server, Angular NgFor is performing its work.
I can guess, img.src performs the request, then my returns in callbacks are not returned as expected, in fact, defaultPrincipalUrl method is not returning nothing as expected, and for that reason Angular is performing the same requests again and again.
But, I don't know the way to solve it in Javascript.
The NgFor in the html looks like this.
<div class="formItem">
<div *ng-for="#principal of localService.defaultPrincipals">
<img src="{{defaultPrincipalUrl(principal)}}" />
</div>
</div>
Where localService.defaultPrincipals is one array which contains image names.
In the Angular2 @Component class, I've the next implementation.
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 '#';
}
});
}