How can i change the image in angular without reloading the page? I have several users and every change in users also has change in image. right now, i need to reload the page to actually see the image change. How not to make it reload anymore?
ts
private image1 = `assets/images/image${localStorage.getItem('user_id')}.jpg`;
html
<img [src]="image1">
select user.ts
onSelectUser(form: NgForm) {
const user = form.value.org;
this.userService.selectedUser(user)
.subscribe(
data => {
console.log(data);
localStorage.setItem('user_id', data.user.id);
},
error => {
console.log(error);
});
}
A simple way to trigger image loading is to reassign src and trigger change detection, for example with setTimeout:
this.userService.selectedUser(user)
.subscribe(
data => {
localStorage.setItem('user_id', data.user.id);
this.image1 = '';
setTimeout(() => {
this.image1 = '...jpg';
});
},
...
Of course, this depends on caching. If image URL stays the same and server caching policy allowed it to be cached (usually this is true for images), it will still loaded from cache. In this case browser cache should be busted with URL change, similarly to how jQuery does for AJAX requests.
Considering that a server is ok with requests that add query string to the URL (usually this isn't a problem), it's simply:
this.userService.selectedUser(user)
.subscribe(
data => {
localStorage.setItem('user_id', data.user.id);
this.image1 = '...jpg?_=' + Date.now();
},
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With