I have a userData object that populate from API
const userdata = {
name: "xyz",
userDocument: []
}
initially userDocument is empty array. but after click user picture. API populates the data as below.
const userdata = {
name: "xyz",
userDocument: [
{
"DocumentUrl": "userImage.jpg"
}
]
}
As I have subscribed to userData and I can see updated image in UI. This is working :)
Problem starts when but when i retake the picture. I get the same string back from server but this time there is different image but the URL is same.
but somehow Subscribe did not able to detect the change(server always give me userImage.jpg) and does not update the image.
I have tried ChangeDetectorRef.detectChanges(), Observer, behavior subject but UI does not update.
I have to restart the app to see changed image.
The browsers rely on the cache if the image URL doesn't change, so a solution is changing the URL by adding a random query string
.
Create a function that accepts a URL as a parameter and returns the URL
concat with query string with any key
and value with timestamp ( the time will always be different on each execution )
getUpdatedImageUrl(url: string): string {
const timestamp = new Date().getTime();
return `${url}?t=${timestamp}`;
}
And whenever you expect that the image might have been updated, recreate the URL
s using the getUpdatedImageUrl
function.
this.userdata.userDocument.forEach(doc => {
doc.DocumentUrl = this.getUpdatedImageUrl(doc.DocumentUrl);
});