简体   繁体   中英

Infinite loop with javascript (Angular NgFor and http request)

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 '#';
        }
    });
}

Use the async pipe.

<div class="formItem">
    <div *ng-for="#principal of localService.defaultPrincipals">
        <img src="{{defaultPrincipalUrl(principal) | async}}" />
    </div>
</div>

The result of defaultPrincipalUrl must be a promise because the callback is async :

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('#');
        }
    });


    });

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM