Why does updating the profile pic not work well?

Whenever I change a user’s profile picture, it reverts to the default user picture after refreshing the page. This happens every time, making it seem like the new profile picture isn’t being saved properly. It could be due to the new image URL not being stored correctly in the database or the application not retrieving the updated URL when the page reloads. To fix this, I need to ensure that the new profile picture URL is correctly saved and fetched from the database every time the page loads.

html :

<img [src]="profileImageUrl || 'assets/images/user.png'" alt="Profile" class="rounded-circle" style="size: 130%;" (click)="triggerFileInput()">

ts :

  constructor(private authService: AuthService) {}

  profileImageUrl: string | null = null;
  private storage = getStorage();

  private readonly DEFAULT_PROFILE_IMAGE_URL = 'assets/images/user.png';
  
  
  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.uploadProfileImage(file);
      };
      reader.readAsDataURL(file);
    }
  }
  
  uploadProfileImage(file: File) {
    const userId = this.authService.getUserId();
    if (userId) {
      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.profileImageUrl = downloadURL;
            this.authService.updateProfileImageUrl(downloadURL);
            this.saveProfileImage(downloadURL);  
          });
        }
      );
    } 
  }      


  ngOnInit() {
    const userId = this.authService.getUserId();
    if (userId) {
      this.loadProfileImage(userId);
    } 
  }
  

  loadProfileImage(userId: string | null) {
    if (userId) {
      const storageRef = ref(this.storage, `profileImages/${userId}/profile.jpg`);
      getDownloadURL(storageRef)
        .then(url => {
          this.profileImageUrl = url;
        })
        .catch(error => {
          this.profileImageUrl = this.DEFAULT_PROFILE_IMAGE_URL;
        });
    } else {
      this.profileImageUrl = this.DEFAULT_PROFILE_IMAGE_URL;
    }
  }
  



  saveProfileImage(imageUrl: string) {
    const userId = this.authService.getUserId(); 
    if (userId) {
      const key = `profileImageUrl_${userId}`;
      localStorage.setItem(key, imageUrl);
    }
  }
    }

authservice.ts :

updateProfileImageUrl(imageUrl: string): Promise<void> {
  const auth = getAuth();
  const user = auth.currentUser;
  if (user) {
    return updateProfile(user, { photoURL: imageUrl })
  } else {
    return Promise.reject('No user is currently logged in.');
  }
}


getUserId(): string | null {
  const user = this.firebaseAuth.currentUser;
  return user ? user.uid : null;
}

1

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.

1

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..

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật