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

相关内容

热门资讯

2026版规律!微乐小程序黑科... 2026版规律!微乐小程序黑科技,手机微乐小程序破解器如何使用(透视)一贯有挂(哔哩哔哩)1、手机微...
第5分钟插件!微乐小程序免费黑... 第5分钟插件!微乐小程序免费黑科技,微乐河南麻将辅助ios(开挂)本来有挂(2026)1、微乐小程序...
透视辅助!微乐小程序黑科技,微... 透视辅助!微乐小程序黑科技,微信小程序微乐辅助器教程(透视)本来存在有挂(哔哩哔哩)1、游戏颠覆性的...
第五分钟插件!微乐小程序免费黑... 第五分钟插件!微乐小程序免费黑科技,微乐自建房辅助软件有哪些功能(开挂)本来有挂(2026)1、微乐...
透视透视!微乐小程序免费黑科技... 透视透视!微乐小程序免费黑科技,微乐陕西小程序破解器(透视)一贯真的有挂(哔哩哔哩)1、微乐陕西小程...
第二分钟安装!微乐小程序免费黑... 第二分钟安装!微乐小程序免费黑科技,微乐斗地主有挂吗(开挂)其实真的是有挂(2026)1、微乐小程序...
来临!微乐小程序黑科技,微乐小... 来临!微乐小程序黑科技,微乐小程序黑科技辅助工具2026最新推荐(透视)竟然是有挂(哔哩哔哩)1、玩...
9分钟开挂!微乐小程序免费黑科... 您好,微乐小程序免费黑科技这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很...
透视讲解!微乐小程序免费黑科技... 透视讲解!微乐小程序免费黑科技,微乐小程序修复系统有用吗(透视)果然真的有挂(哔哩哔哩)1、进入到微...
第4分钟安装!微乐小程序免费黑... 第4分钟安装!微乐小程序免费黑科技,微乐小程序辅助器代理(开挂)好像是有挂(2026)微乐小程序免费...