7

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?

1
  • 1
    Its not an Angular problem. Its a cache problem. Change your url format to allow versioning or add a ? add the end of your url following by your file version. Commented Dec 13, 2016 at 15:57

1 Answer 1

22

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());
Sign up to request clarification or add additional context in comments.

3 Comments

I thought about using a cache breaker like this but was hoping there was a cleaner ng2 way. So is there no way we can refresh the image element without adding to the url?
The cache bust has nothing to do with Angular 2, that's just a "web thing". An alternative could be that you fetch the image itself, base64 encode it and update the source with the base64 data ...
Thanks for the ideas. It was what I suspected. I will have a play with it and see what I can come up with.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.