Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refresh an image with angular

I need to refresh an image that I load like this:

<img [src]="linkPicture" alt="profile photo" width="150px" height="150px">

Into the typescript file I have a variable this.linkPicture that I store initially the link. When I update the picture don't refresh. I set the variable again....

Here is part of my typescript code

public linkPicture          : string;

Set the variable initially

this.service.GetProfile(id).subscribe(resp => {
        .....
        this.linkPicture = resp.Photo;
        console.log(resp); //this show the photo
    });

When I update the picture

let dialogRef = this.dialog.open(DialogUploadPhotoComponent, {
        data: {
            patientID: this.ss.getCurrentUserApi().PatientID
        },
        width : "550px",
        });
        dialogRef.afterClosed().subscribe(result => {
            if(result != undefined){
                console.log(result);
                this.linkPicture = result;   //I set the new picture.                   
            }
        });
like image 306
Yoedusvany Hdez Avatar asked Sep 13 '18 14:09

Yoedusvany Hdez


People also ask

How do you refresh a photo?

Reload Images. Reload images in Tab/Window using context menu. This extensions provides a simple way to reload image using context menu. Just right on image and select "reload this image" or right click on page and click "reload all images" in Tab or Window.

How do I refresh an image in HTML?

newImage. src = "http://localhost/image.jpg?" + new Date(). getTime(); This will append the current timestamp automatically when you are creating the image, and it will make the browser look again for the image instead of retrieving the one in the cache.


1 Answers

You can append a timestamp query to the image URL to force the browser to reload the image. This shouldn't have any negative side effects with the server hosting the image.

Update the template to call a function:

<img [src]="getLinkPicture()" alt="profile photo" width="150px" height="150px">

Compute the URL using an optional timeStamp value:

public getLinkPicture() {
     if(this.timeStamp) {
        return this.linkPicture + '?' + this.timeStamp;
     }
     return this.linkPicture;
}

When the URL is changed. Create a new timeStamp value.

public setLinkPicture(url: string) {
     this.linkPicture = url;
     this.timeStamp = (new Date()).getTime();
}

Even if the URL is the same the timestamp changes, and this forces the browser to reload the image.

like image 82
Reactgular Avatar answered Sep 20 '22 15:09

Reactgular