首页 > 解决方案 > 功能不会停止运行角度 5

问题描述

我遇到了一些麻烦,我无法弄清楚我哪里出错了......

我有一个功能可以从数据库中获取用户个人资料图片,如下所示..

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>

组件.ts

userPic(userId) {
  this._profileService.getProfilePictureByUserId(userId).subscribe(result => 
{
    return 'data:image/jpeg;base64,' + result.profilePicture;
  });
}

trackByFn(index: any , item: any) {
    return index;
}

但应用程序仍然崩溃

标签: javascriptangulartypescript

解决方案


在属性中返回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>

请记住导入必要的模块和库。


推荐阅读