简体   繁体   中英

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?

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());

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