Функция не остановит бега угловой 5 - PullRequest
0 голосов
/ 27 апреля 2018

У меня небольшие проблемы, я не могу понять, где я иду не так ...

У меня есть функция, которая получает изображение профиля пользователя из базы данных, как это ..

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 раз

но каждый раз, когда я запускаю свое приложение, это происходит и мое приложение падает ... Я не уверен, что я делаю неправильно ??

enter image description here

EDIT

Я пытался сделать это ...

<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;
}

но приложение все еще падает

Ответы [ 2 ]

0 голосов
/ 27 апреля 2018

Я бы предложил переместить ваш асинхронный метод в компонент и сохранить вызываемые изображения в новый массив, а затем выполнить цикл в 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 (), это также может вызвать проблемы.

0 голосов
/ 27 апреля 2018

Вернуть Observable<string> и использовать async pipe в атрибуте [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>

Не забудьте импортировать необходимые модули и библиотеки.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...