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、许多玩家不知...
研究成果!微扑克辅助软件,微扑... 研究成果!微扑克辅助软件,微扑克有挂么(微扑克)本来存在有挂(有挂实锤)-哔哩哔哩微扑克辅助软件软件...
终于清楚!微扑克辅助挂,微扑克... 终于清楚!微扑克辅助挂,微扑克如何让系统发好牌(微扑克)确实是有挂(有挂秘籍)-哔哩哔哩1、微扑克如...
重大通报!微扑克ai辅助工具,... 重大通报!微扑克ai辅助工具,微扑克透牌(微扑克)切实有挂(有挂猫腻)-哔哩哔哩进入游戏-大厅左侧-...
普及知识!微扑克有ai吗,微扑... 普及知识!微扑克有ai吗,微扑克如何让系统发好牌(微扑克)本来有挂(存在有挂)-哔哩哔哩1、上手简单...
一分钟教会你!微扑克有挂么,微... 一分钟教会你!微扑克有挂么,微扑克ai机器人(微扑克)好像是真的有挂(真的有挂)-哔哩哔哩1、微扑克...
玩家实测!微扑克辅助工具,微扑... 玩家实测!微扑克辅助工具,微扑克如何让系统发好牌(微扑克)真是存在有挂(详细教程)-哔哩哔哩1、全新...
玩家必看科普!微扑克辅助提高胜... 玩家必看科普!微扑克辅助提高胜率,微扑克透牌(微扑克)原来有挂(有挂神器)-哔哩哔哩微扑克辅助提高胜...
查到实测辅助!微扑克辅助工具怎... 查到实测辅助!微扑克辅助工具怎么下载,微扑克有挂么(微扑克)确实有挂(有挂猫腻)-哔哩哔哩;1、微扑...
最新研发!微扑克有挂么,微扑克... 最新研发!微扑克有挂么,微扑克有挂么(微扑克)果然存在有挂(真的有挂)-哔哩哔哩1)微扑克有挂么辅助...