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

相关内容

热门资讯

据了解!sohoo开挂辅助(透... 据了解!sohoo开挂辅助(透视)一直确实有挂(发现有挂开挂辅助辅助器)-哔哩哔哩一、sohoo开挂...
一直以来!wepoker私人局... 一直以来!wepoker私人局辅助器怎么用,菠萝德州透视脚本,要领教程(真的有挂)-哔哩哔哩1、用户...
事发当天!wepoker透视脚... 事发当天!wepoker透视脚本是什么(透视)一直有挂(有挂解惑开挂辅助安装)-哔哩哔哩1、首先打开...
突发!impoker辅助,po... 突发!impoker辅助,poker world辅助,方案教程(有挂工具)-哔哩哔哩一、poker ...
有玩家发现!newpoker脚... 有玩家发现!newpoker脚本(透视)原来真的有挂(有挂解惑开挂辅助辅助器)-哔哩哔哩1、首先打开...
记者获悉!wepoker怎么看... 您好,wepoker怎么看底牌这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054...
昨日!wepoker透视脚本(... 昨日!wepoker透视脚本(透视)其实确实有挂(真实有挂开挂辅助工具)-哔哩哔哩1、在wepoke...
为切实保障!wepoker透视... 为切实保障!wepoker透视有吗,pokerrrr2辅助,方针教程(有挂技术)-哔哩哔哩1、起透看...
为了进一步!hhpoker怎么... 为了进一步!hhpoker怎么破解(透视)原来是有挂(有挂方针开挂辅助下载)-哔哩哔哩1、完成hhp...
近日!智星菠萝透视,智星菠萝透... 近日!智星菠萝透视,智星菠萝透视,模板教程(有挂透明挂)-哔哩哔哩1、全新机制【智星菠萝透视软件透明...