我有点麻烦,我无法弄清楚我哪里出错......
我有一个从数据库中获取用户个人资料图片的功能,如此...
userPic(userId) {
this._profileService.getProfilePictureByUserId(userId).subscribe(result => {
return 'data:image/jpeg;base64,' + result.profilePicture;
});
}
然后在我的HTML中
<div *ngFor="let data of returnedData">
<img [src]="userPic(data.lastModifiedUser.id)" alt="User Profile Picture">
</div>
所以我在数据数组中找回了99个对象,因此循环99次
但每次我运行我的应用程序时都会发生这种情况 我的应用程序崩溃了...我不知道我做错了什么?
修改
我试过这样做......
<div *ngFor="let data of data; let i = index; trackBy: trackByFn">
<img [src]="userPic(angel.lastModifiedUser.id)" alt="User Profile Picture">
</div>
component.ts
userPic(userId) {
this._profileService.getProfilePictureByUserId(userId).subscribe(result =>
{
return 'data:image/jpeg;base64,' + result.profilePicture;
});
}
trackByFn(index: any , item: any) {
return index;
}
但应用程序仍在崩溃
答案 0 :(得分:1)
返回Observable<string>
并在async
属性中使用[src]
管道,并在trackby
指令中使用*ngFor
userPic(profilePictureId, userId): Observable<string> {
if (profilePictureId && userId && this.tenantId) {
console.log('getprofilepicture');
return this._profileService.getFriendProfilePictureById(profilePictureId, userId, this.tenantId).pipe(map(result => {
if (result && result.profilePicture) {
return '../../../assets/img/default-profile-picture.png';
// return 'data:image/jpeg;base64,' + result.profilePicture;
} else {
return '../../../assets/img/default-profile-picture.png';
}
}));
} else {
console.log('didnt run');
return Observable.of('../../../assets/img/default-profile-picture.png');
}
}
trackByFnById(index, item) {
return item.lastModifiedUser.id;
}
模板
<div *ngFor="let data of returnedData; trackBy: trackByFnById">
<img [src]="userPic(data.lastModifiedUser.profilePictureGuid, data.lastModifiedUser.id) | async" alt="User Profile Picture">
</div>
请记住导入必要的模块和库。
答案 1 :(得分:1)
我建议你将async方法移动到你的组件并将你调用的图片保存到一个新的数组中,然后像你这样在你的html中循环:
private dataset = []; // guessing this is already populated with user information
public userPics = []; // use this to store your user pictures
private getUserPics(): void { // call this after you have filled you dataset with user information if that would be in your ngOnInit() or some other method
for (const id of this.dataset) {
this._profileService.getProfilePictureByUserId(id)
.subscribe(
res => { this.userPics.push('data:image/jpeg;base64,' + res.profilePicture); },
err => { console.log(err); }
);
}
}
<div *ngFor="let pic of userPics">
<img [src]="pic" alt="User Profile Picture">
</div>
您可能还想发布_profileService.getProfilePictureByUserId()函数代码,这可能会导致您遇到问题。