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异步管道在图像源更新时无效的问题。具体使用哪一种方法取决于你的应用需求和具体情况。

相关内容

热门资讯

透视存在!hhpoker万能辅... 透视存在!hhpoker万能辅助器,拱趴大菠萝有挂吗,技巧教程(素来存在有挂)hhpoker万能辅助...
透视最新!aapoker辅助器... WePoke高级策略深度解析‌;透视最新!aapoker辅助器怎么用,wepoker辅助器是真的吗,...
透视科技!红龙poker脚本,... 透视科技!红龙poker脚本,wepoker正确养号方法,细节方法(本然有挂);值得一提的是,红龙p...
透视讲解!hhpoker辅助软... 透视讲解!hhpoker辅助软件下载,wpk辅助器,扑克教程(原来有挂)是由北京得hhpoker辅助...
透视真的!wepoker辅助器... 透视真的!wepoker辅助器是真的的吗,aapoker辅助软件合法吗,总结教程(切实真的有挂);最...
透视好友!wepoker辅助透... 透视好友!wepoker辅助透视软件,拱趴大菠萝有挂吗,技巧教程(切实真的是有挂);(需添加指定Q群...
透视辅助!wpk辅助工具下载,... 透视辅助!wpk辅助工具下载,wepoker怎么看牌型,解密教程(固有真的是有挂)是一款可以让一直输...
透视计算!wepoker辅助器... 透视计算!wepoker辅助器安装包,哈糖大菠萝怎么挂,微扑克教程(原来有挂)是一款可以让一直输的玩...
透视模拟器!智星菠萝可以辅助吗... 透视模拟器!智星菠萝可以辅助吗,德州辅助工具到底怎么样,2025新版(好像真的有挂);亲真的是有正版...
透视代打!红龙poker脚本,... 《红龙poker脚本软件透明挂》是一款多人竞技的红龙poker脚本辅助透视游戏,你将微扑克对手来到同...