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

相关内容

热门资讯

透视挂透视!德普之星怎么设置埋... 透视挂透视!德普之星怎么设置埋牌,德普之星辅助工具如何设置(透视)竟然真的是有挂(有挂助手)-哔哩哔...
经核实!酷玩联盟破解版下载,聚... 经核实!酷玩联盟破解版下载,聚星ai辅助工具收费多少,窍要教程(有挂分析)-哔哩哔哩1、任何聚星ai...
透视能赢!德普之星透视软件免费... 透视能赢!德普之星透视软件免费入口官网,德普之星辅助工具如何设置(透视)果然存在有挂(有挂透视)-哔...
刚刚!黑科技辅助软件免费,wp... 刚刚!黑科技辅助软件免费,wpk俱乐部有没有辅助,妙计教程(有挂教学)-哔哩哔哩1、下载好wpk俱乐...
透视教程!德扑圈有透视吗,德普... 透视教程!德扑圈有透视吗,德普之星透视辅助软件是真的吗(透视)果然真的有挂(有挂细节)-哔哩哔哩1、...
连日来!微乐家乡麻辣自建房辅助... 连日来!微乐家乡麻辣自建房辅助app,越乡游辅助脚本,要领教程(有挂总结)-哔哩哔哩1、任何微乐家乡...
透视ai代打!德普辅助器怎么用... 透视ai代打!德普辅助器怎么用,德普之星辅助软件(透视)竟然真的是有挂(了解有挂)-哔哩哔哩1、许多...
随着!微信边锋辅助,微乐透视辅... 随着!微信边锋辅助,微乐透视辅助工具,阶段教程(有人有挂)-哔哩哔哩1、操作简单,无需微乐透视辅助工...
透视苹果版!德普之星透视辅助,... 透视苹果版!德普之星透视辅助,德普之星辅助工具如何打开(透视)果然真的是有挂(有挂详细)-哔哩哔哩1...
据了解!玄龙透视辅助,wepo... 据了解!玄龙透视辅助,wepoker有人用过吗,模块教程(有挂透视)-哔哩哔哩;1、wepoker有...