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

相关内容

热门资讯

透视课程!aapoker辅助插... 透视课程!aapoker辅助插件工具,aapoker辅助插件工具(透视)切实有脚本脚本(哔哩哔哩)1...
透视妙招!德州局透视脚本免费版... 透视妙招!德州局透视脚本免费版下载手机版,aapoker真的假的(透视)本来有挂(哔哩哔哩)1、下载...
透视方式!德州透视竞技联盟,约... 透视方式!德州透视竞技联盟,约局吧德州真的存在透视吗(透视)一贯有脚本方法(哔哩哔哩)一、约局吧德州...
透视阶段!aa poker透视... 透视阶段!aa poker透视软件,aapoker透视插件(透视)好像真的是有脚本挂(哔哩哔哩)1、...
透视步骤!wpk俱乐部怎么作必... 透视步骤!wpk俱乐部怎么作必弊,wpk辅助是什么(透视)确实真的是有透视软件(哔哩哔哩)1)wpk...
透视诀窍!大菠萝辅助器,哈糖大... 透视诀窍!大菠萝辅助器,哈糖大菠萝挂(透视)确实真的是有脚本方法(哔哩哔哩)在进入大菠萝辅助器软件靠...
透视练习!哈糖大菠萝攻略,约局... 透视练习!哈糖大菠萝攻略,约局吧德州有挂吗(透视)本来是真的透视器(哔哩哔哩);1、约局吧德州有挂吗...
透视机巧!拱趴大菠萝万能辅助器... 透视机巧!拱趴大菠萝万能辅助器,wepokerplus到底是挂了吗(透视)果然真的是有挂(哔哩哔哩)...
透视大纲!德普之星辅助器怎么用... 透视大纲!德普之星辅助器怎么用,德普之星辅助工具如何设置(透视)好像真的有透视软件(哔哩哔哩)1、德...
透视法子!wpk辅助哪里买,w... 透视法子!wpk辅助哪里买,wpk显示有作必弊(透视)竟然有透视工具(哔哩哔哩)1、wpk显示有作必...