html - 在异步管道中设置 img src 对象 url 时防止图像闪烁

标签 html css angular typescript

我有一个 JWT 授权的图像端点,所以我们不能直接链接到 html 中的图像 url。

解决方法是让这个异步管道以正确的授权加载图像(通过 http 拦截器,未显示),并将 img.src 属性设置为“对象”url。

HTML:

<img [attr.src]="environment.apiUrl + 'users/image/' + userId | secureImage | async" alt="Avatar" />

管道:

import { Pipe, PipeTransform } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Pipe({
    name: 'secureImage'
})
export class SecureImagePipe implements PipeTransform {

    constructor(private http: HttpClient, private sanitizer: DomSanitizer) { }

    transform(url): Observable<SafeUrl> {
        return this.http
            .get(url, { responseType: 'blob' })
            .pipe(map(val => this.sanitizer.bypassSecurityTrustUrl(URL.createObjectURL(val))));
    }
}

正如您在此 GIF 中所见,当图像从加号(静态)变为荷马大脑(通过此管道加载)时,会出现非常短的闪烁,显示经典的“找不到图像”连同替代文本(头像)。

Flicker

如何防止这种闪烁?

更新:删除“alt”属性会删除“损坏的图像”图像,看起来好多了。

从这里开始:

<img [attr.src]="environment.apiUrl + 'users/image/' + userId | secureImage | async" alt="Avatar" />

为此:

<img [attr.src]="environment.apiUrl + 'users/image/' + userId | secureImage | async" />

我将这个问题保持开放状态,因为可能有些人必须具有 alt 属性,所以我的解决方案对他们不起作用。

最佳答案

当您单击按钮并加载图像时,有一小段时间未从服务器完全加载图像, 将显示替代文本。

为防止出现这种情况,请通过组件/服务从服务器下载图像,并仅在图像完全加载完成后才设置 src。

关于html - 在异步管道中设置 img src 对象 url 时防止图像闪烁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61117581/

相关文章:

Javascript,CSS : Get element by style attribute

html - Angular2 如何在 HTML5 模板中显示 localStorage 值?

javascript - Angular 2 : Asynchronous upload array of files

html - 模态不渲染到屏幕中央

css - Yeoman Web 应用程序 SASS 无法加载

html - 连续居中两个 col-sm-6 + 一些基本的 boostrap 混淆

html - Bootstrap 4 将侧边栏折叠成导航栏下拉菜单

typescript - @ngrx/store-devtools : instrumentStore() returns an array of objects instead of providers

javascript - 如何在通过 XSLT 创建 HTML 时发送 "defer"属性?

javascript - 在 Bootstrap 中切换菜单会停止 <a href =""> 工作