Ben Cameron
Ben Cameron

Reputation: 4413

Angular2 update image [src] after server upload

I have an Angular 2 app. It has a component that allows a user to crop and upload an image to the server. The parent component shows the image in a src tag. I need to be able to update this src tag once an updated image is uploaded. The link in the src tag will always be the same. Once I manually refresh the browser I see the newly uploaded image.

Here is my image in the HTML. The URL is defined in the component...

<img  [src]="url" />

The parent component hosts the image upload component like so...

<imageUploadCropper [postUrl]="postimageProfileUrl"></imageUploadCropper>

The image upload component will upload an image like so...

    const formData = new FormData();
    formData.append("uploadedImage", this.data.image);

    this._http.post(this.postUrl, formData, { headers: headers })
        .subscribe();

How do I reload an image in Angular2? Should I just reload the page/route or this there another way? Would using Zones help somehow?

Upvotes: 7

Views: 9473

Answers (1)

rzelek
rzelek

Reputation: 4013

You have to change src to reload. One of the solutions can be adding random string to the end of the url.

this._http.post(this.postUrl, formData, { headers: headers })
    .subscribe(() => this.url += '?random+\=' + Math.random());

Upvotes: 22

Related Questions