Me gustaría mostrar los datos de los usuarios, pero tengo un problema al mostrar las imágenes de perfil correctas. Si un usuario no tiene una imagen de perfil, aparece "indefinido" en la consola. Si un usuario tiene una imagen de perfil, se mostrará la misma imagen para todos los usuarios. Necesito ayuda para encontrar el error en mi código.
export interface UserData { id: number, name: string } export interface UserWithImage extends UserData{ image?: string } export interface UserProfileImage { id: number, url: string }Después de obtener los datos necesarios de los servicios, intento insertar la imagen de perfil en el archivo userData.
datos-de-usuario.ts
userData: UserWithImage[]; userProfiles: UserProfileImage[]; userProfileImage: UserProfileImage[]; getUserData() { this.userData = this.userService.getData(); this.userProfiles = await this.imagesService.getProfilePicture(this.userData?.map(u => u.id)); this.userProfileImage = this.userProfiles.filter(u => u.url); this.userData?.forEach((data, i) => { data.image = this.userProfileImage[i].url; }); }imágenes.servicio.ts
public async getProfilePicture(ids: number[]): Promise<UserProfileImage[]> { const toLoad = ids.filter(id => !this.userProfileImages.find(up => up.id === id)).map(u => u); if (toLoad || toLoad.length) { const loaded = (await firstValueFrom(this.httpClient.post<UserProfile[]> (this.imgService.getServiceUrl(customersScope, `${basePath}settings/users/profil`), JSON.stringify(toLoad), {headers}))).map(sp => { return { id: sp.userId, url: sp.profilepicId ? this.imgService.getServiceUrl(customersScope, `${basePath}web/download/profilepic/${sp.profilepicId}/users/${sp.userId}`, true) : '' } as UserProfileImage }); this.userProfileImages = [...loaded, ...this.userProfileImages]; } return this.userProfileImages; }datos-usuario.html
<div ngFor="data of userData"> <etc-profil [name]="data.name" [image]="data.image"></etc-profil> </div>this.userData = this.userService.getData(); ¿Es esta una función asíncrona (es decir, te falta un await )?
this.userProfiles = await this.imagesService.getProfilePicture(this.userData?.map(u => u.id)); Esta línea fallaría si es this.userData es una promesa. this.userProfiles no estaría undefined debido al uso de encadenamiento opcional ( ?. )
this.userProfileImage = this.userProfiles.filter(u => u.url); Esta línea parece no hacer nada, el predicado del filtro dice que se incluye cualquier cosa con una propiedad de url que no sea null o undefined , pero la interfaz dice que la url no es opcional y no es compatible con null o undefined .
this.userData?.forEach((data, i) => { data.image = this.userProfileImage[i].url; }); Nuevamente, si this.userData es una promesa, esto no hará nada debido al encadenamiento opcional.
Si se ejecuta, se supone que existe una relación de uno a uno entre los usuarios y las imágenes de perfil (el recuento y el orden del índice deben ser los mismos).
No consideré la implementación de getProfilePicture porque creo que estos problemas deben resolverse primero.