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、进入到越乡游义乌微信小程序...
这一问题亟待解决!黑科技软件大... 这一问题亟待解决!黑科技软件大全!本来真的有辅助软件(有挂辅助)-哔哩哔哩进入游戏-大厅左侧-新手福...
备受关注的!拱趴大菠萝系统规律... 备受关注的!拱趴大菠萝系统规律!确实是真的辅助修改器(有挂技巧)-哔哩哔哩1、用户打开应用后不用登录...
突发!战皇大厅辅助那个可靠!原... 突发!战皇大厅辅助那个可靠!原来真的是有辅助挂(有挂头条)-哔哩哔哩所有人都在同一条线上,像星星一样...
近年来!手机科乐辅助!原来真的... 您好,手机科乐辅助这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054】很多玩家在...
据报道!南宁友乐辅助!切实真的... 据报道!南宁友乐辅助!切实真的有辅助神器(有挂教程)-哔哩哔哩1)南宁友乐辅助免费钻石:进一步探索南...
据监测!佛手十三道辅助!果然是... 据监测!佛手十三道辅助!果然是有辅助挂(有挂讲解)-哔哩哔哩1、每一步都需要思考,不同水平的挑战会更...
今天下午!奇迹陕西游戏辅助器!... 今天下午!奇迹陕西游戏辅助器!其实是真的辅助挂(存在有挂)-哔哩哔哩1、上手简单,内置详细流程视频教...
做出回应!衢州多莱辅助器!切实... 做出回应!衢州多莱辅助器!切实真的是有辅助安装(真的有挂)-哔哩哔哩1、全新机制【衢州多莱辅助器ai...