Whenever I change a user’s profile pic , the same thing happens to the rest of the other users ( their profile pic becomes the one of the user whom profile pic got updated manually ) and storage in firebase is working well, every new pic change , it gets added
html :
<img [src]="profileImageUrl || 'assets/images/user.png'" alt="Profile" class="rounded-circle" style="size: 130%;" (click)="triggerFileInput()">
ts :
profileImageUrl: string | null = null;
private storage = getStorage();
constructor(@Inject(PLATFORM_ID) private platformId: Object) {}
triggerFileInput() {
this.fileInput.nativeElement.click();
}
onFileSelected(event: Event) {
const input = event.target as HTMLInputElement;
if (input.files && input.files[0]) {
const file = input.files[0];
const reader = new FileReader();
reader.onload = (e: any) => {
this.profileImageUrl = e.target.result;
this.saveProfileImage(this.profileImageUrl!);
};
reader.readAsDataURL(file);
this.uploadProfileImage(file);
}
}
uploadProfileImage(file: File) {
const userId = this.authService.getUserId(); // Ensure you get the current user's ID
const storageRef = ref(this.storage, `profileImages/${userId}/${file.name}`);
const uploadTask = uploadBytesResumable(storageRef, file);
uploadTask.on('state_changed', (snapshot) => {},
() => {
getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
this.saveProfileImage(downloadURL);
});
}
);
}
ngOnInit() {
if (isPlatformBrowser(this.platformId)) {
this.loadProfileImage();
}
}
saveProfileImage(imageUrl: string) {
this.authService.updateProfileImage(imageUrl).then(() => {
this.profileImageUrl = imageUrl;
});
}
loadProfileImage() {
this.authService.getProfileImage().then(imageUrl => {
this.profileImageUrl = imageUrl || 'assets/images/user.png';
});
}
}
2
Answers
It looks to me as if the component is used for every image.
The method "saveProfileImage" somehow saves the image with the AuthService.
This AuthService is also used in "loadProfileImage" to load the latest image per event.
If you now have this AuthService provide in root, all ImageComponents use the same instance and are notified among themselves.
You would have to add the service to the provider of the ImageComponent if this is the problem.
That would be my suggestion based on the showed code.
Firstly, ensure that when you updating the profile pic, it is correctly stroing against the respective unique id(user id) of the user.
check the same in the save scenario also.
While when you retrieving the profile pic to dispaly, you shoould pass the unique id(user id) to get the profile pic, so each user will have their respective unique id’s and will get their profile pics against their id’s.
I hope this would help in some way..