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显示有作弊,微... 科普透视!wpk显示有作弊,微乐自建房脚本免费下载,妙计教程(有挂透视)-哔哩哔哩一、wpk显示有作...
揭露透视!德普之星辅助工具如何... 揭露透视!德普之星辅助工具如何打开,微信微乐陕西挖坑小程序下载,指南书教程(有挂方法)-哔哩哔哩1、...
揭露透视!wepoker透视最... 揭露透视!wepoker透视最简单三个步骤,微信小程序微乐辅助器真吗,教程书教程(有挂解密)-哔哩哔...
推荐透视!德州局怎么透视,微信... 推荐透视!德州局怎么透视,微信小程序自建房记牌器,练习教程(新版有挂)-哔哩哔哩1)德州局怎么透视免...
科普透视!wepoker作弊方... 科普透视!wepoker作弊方法,微信小程序微乐房间有技巧吗,绝活教程(了解有挂)-哔哩哔哩1、不需...
关于透视!拱趴大菠萝十三水作弊... 关于透视!拱趴大菠萝十三水作弊,微乐自建房辅助多少钱一个月,机巧教程(了解有挂)-哔哩哔哩1、首先打...
详情透视!wepoker怎么拿... 详情透视!wepoker怎么拿到好牌,微乐广西麻辣,练习教程(有挂方针)-哔哩哔哩1、wepoker...
揭露透视!哈糖大菠萝破解器,微... 揭露透视!哈糖大菠萝破解器,微信卡五星小程序辅助,攻略教程(今日头条)-哔哩哔哩哈糖大菠萝破解器脚本...
辅助透视!德普之星透视软件免费... 辅助透视!德普之星透视软件免费入口官网,微乐河南小程序辅助器免费,讲义教程(新版有挂)-哔哩哔哩1、...