Angular异步管道对图像源更新无效。
创始人
2024-10-30 12:00:13
0

问题描述: 在Angular应用中,使用异步管道来加载图像源时,图像源的更新可能无效。

解决方法:

  1. 使用管道的纯函数版本: 在管道中使用纯函数版本,确保输入和输出的值都是不可变的。这样即使图像源发生变化,管道也会正确地更新。
@Pipe({
  name: 'asyncImage'
})
export class AsyncImagePipe implements PipeTransform {
  transform(source: string | null): SafeUrl | null {
    return source ? this.sanitizer.bypassSecurityTrustUrl(source) : null;
  }
}
  1. 使用管道的非纯函数版本: 如果管道中的变量不是不可变的,可以使用管道的非纯函数版本。这样,每次检测时都会重新计算管道的输出值。
@Pipe({
  name: 'asyncImage',
  pure: false
})
export class AsyncImagePipe implements PipeTransform, OnDestroy {
  private sourceSubscription: Subscription | null = null;
  private latestSource: string | null = null;
  private latestSafeUrl: SafeUrl | null = null;

  constructor(private sanitizer: DomSanitizer) {}

  transform(source: string | null): SafeUrl | null {
    if (source !== this.latestSource) {
      this.latestSource = source;
      if (this.sourceSubscription) {
        this.sourceSubscription.unsubscribe();
        this.sourceSubscription = null;
      }
      this.latestSafeUrl = null;
      if (source) {
        this.sourceSubscription = this.loadImage(source).subscribe(url => {
          this.latestSafeUrl = this.sanitizer.bypassSecurityTrustUrl(url);
        });
      }
    }
    return this.latestSafeUrl;
  }

  ngOnDestroy() {
    if (this.sourceSubscription) {
      this.sourceSubscription.unsubscribe();
    }
  }

  private loadImage(source: string): Observable {
    return new Observable(observer => {
      const image = new Image();
      image.onload = () => {
        observer.next(source);
        observer.complete();
      };
      image.src = source;
    });
  }
}

这两种方法都可以解决Angular异步管道在图像源更新时无效的问题。具体使用哪一种方法取决于你的应用需求和具体情况。

相关内容

热门资讯

必备透视!德州辅助工具到底怎么... 必备透视!德州辅助工具到底怎么样!总是是真的有辅助神器(有挂技巧)-哔哩哔哩1、进入游戏-大厅左侧-...
解迷透视!wpk辅助哪里买,w... 解迷透视!wpk辅助哪里买,wepoker免费脚本咨询,经验教程(真实有挂)-哔哩哔哩1、该软件可以...
解谜透视!聚星ai辅助工具激活... 解谜透视!聚星ai辅助工具激活码!真是是有辅助app(证实有挂)-哔哩哔哩该软件可以轻松地帮助玩家将...
专业透视!wpk透视工作室,w... 专业透视!wpk透视工作室,wepoker辅助是真的吗,举措教程(有挂详情)-哔哩哔哩1、wepok...
教你透视!德州局怎么透视!果然... 教你透视!德州局怎么透视!果然真的是有辅助工具(有挂细节)-哔哩哔哩1、德州局怎么透视公共底牌简单,...
详情透视!如何下载wepoke... 详情透视!如何下载wepoker安装包,wepoker透视有没有,秘籍教程(果真有挂)-哔哩哔哩1、...
推荐透视!we poker免费... 推荐透视!we poker免费辅助器!都是是真的有辅助app(有挂教学)-哔哩哔哩1、让任何用户在无...
解密透视!约局吧怎么看有没有挂... 解密透视!约局吧怎么看有没有挂,红龙poker辅助器免费观看,方案教程(有挂方略)-哔哩哔哩;1、每...
详情透视!红龙poker有辅助... 详情透视!红龙poker有辅助吗!竟然真的是有辅助插件(有挂方略)-哔哩哔哩1、操作简单,无需红龙p...
有挂透视!hhpoker到底可... 有挂透视!hhpoker到底可以作必弊吗,德州局hhpoker,阶段教程(有挂规律)-哔哩哔哩1、h...