避免在[src]中重新加载图像

时间:2018-01-30 21:25:34

标签: angular firebase rxjs observable angular2-observables

我有一个应用程序,显示带有个人资料图片的用户列表。 当我更新此用户的值时,图像会重新加载,因为可观察列表会再次发出所有数据。 我怎么能避免这个?

<div *ngFor="let user of users">
<img [src]="user.profilepic"/> {{user.name}} <button (click)="updateUser(user)">Update</button>
</div>

TS:

this.userProvider.getUserList()
      .distinct()
      .subscribe(data => {
        this.users = data
      })

我希望这个distinct()函数可以完成这项工作,但没有成功。 该应用程序使用离子3结合firebase实时数据库数据和使用公共URL下载的firebase存储图片

3 个答案:

答案 0 :(得分:7)

您需要使用 trackBy

<div *ngFor="let user of users; trackBy: trackBy">
    <img [src]="user.profilepic"/> {{user.name}} <button (click)="updateUser(user)">Update</button>
</div>

然后在你的组件中定义:

public trackBy(index, user) {
    return user.id; // or any other identifier
}

这将阻止 Angular 在 DOM 中创建元素。

答案 1 :(得分:0)

<div *ngFor="let user of users">
<img [src]="user.profilepic"/> {{user.name}} <button (click)="updateUser(user)">Update</button>
我假设......成功更新后,您正在尝试再次获取所有用户列表
updateUser(user){
//after the successful update
        this.userProvider.getUserList()
              .distinct()
              .subscribe(data => {
                this.users = data
             })
}

而不是获取成功的更新......您只能更新列表中的一个用户(更新的用户)

updateUser(user){
    //after the successful update

    this.userlist.find(a=> a.id== user.id).name = user.name;

    //can update whatever field you have uoadated
}

答案 2 :(得分:-1)

您必须将单个用户对象更新为重新分配用户数组以刷新 html

this.userProvider.getUserList()
      .distinct()
      .subscribe(data => {
        if(!this.users) {
         this.users = data
        }
        else {
           for(let user of data) {
                 /* TODO find the user in this.users array & updated required properties, if user not found add it to this.users array*/ 
           }
        }
      })
相关问题