Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 update image [src] after server upload

Tags:

angular

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?

like image 911
Ben Cameron Avatar asked Dec 13 '16 15:12

Ben Cameron


1 Answers

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());
like image 188
rzelek Avatar answered Nov 10 '22 20:11

rzelek