首页 > 解决方案 > Angular 7 - 轮询时闪烁的图像

问题描述

我正在开发一个聊天平台。目前我正在从 API 调用中轮询图像。但是,如果我要在聊天平台上上传图片,每次我调用 api 加载所有消息时,图片都会周期性地闪烁。有解决方法吗?

如果我在谷歌浏览器网络选项中关闭了禁用缓存选项,或者如果我要使用隐身模式,则不会发生闪烁。

聊天组件.ts

setupMessagePoll(chatId: string, period: number): Subscription {
    return interval(period).subscribe(() => {
      this.chatService.listChatMessages(id).subscribe(messages=> 
      this.messages = messages)
    });
 }

setImageAsBackground(message) {
    const a = this.sanitizer.bypassSecurityTrustStyle(
      'background-image: url("' +
        this.attachmentSrc(message) +
        '"); ' +
        'background-repeat: no-repeat; ' +
        'background-size: cover;' +
        'background-position: center;'
    );
   return a;
}


attachmentSrc(m: Message): string {
    if (m.attachmentId === this.placeholderUpload) {
      return ['assets', 'placeholder-uploading.png'].join('/');
    } else {
      return [
        environment.apiBasePath,
        'chat',
        m.chatId,
        'image',
        m.attachmentId,
      ].join('/');
    }
  }

trackByFn(index, message: Message) {  //newly added trackByFn function
    return message.id;
}

聊天组件.html

<ng-container *ngFor="let message of messages; last as isLast; trackBy: trackByFn">
   <div class="col-12 p-0 d-flex" [ngClass]="{ 'justify-content-end': message.authorId === self.id }">
    <!-- Profile image  -->
        <div
            class="message-attachment"
            *ngIf="message.attachmentId"
            [style]="setImageAsBackground(message)"
            (click)="setLightboxImage(attachmentSrc(message))"
          ></div>
</ng-container>

感谢你的帮助!

标签: angularchatflicker

解决方案


推荐阅读