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

相关内容

热门资讯

玩家实测“川川云脚本破解”素来... 玩家实测“川川云脚本破解”素来有开挂辅助插件(今日头条);无需打开直接搜索微信(136704302)...
玩家必看“拱趴大菠萝挂怎么安装... 玩家必看“拱趴大菠萝挂怎么安装”本来有辅助软件(有挂方法)1、下载安装好拱趴大菠萝挂怎么安装,进入游...
推荐一款“德普之星透视辅助软件... 推荐一款“德普之星透视辅助软件”本然有辅助插件(有挂方略);无需打开直接搜索加(薇:13670430...
透视安装“如何下载河洛杠次脚本... >>您好:如何下载河洛杠次脚本确实是有挂的,很多玩家在这款如何下载河洛杠次脚本游戏中打牌都会发现很多...
发现玩家“大唐游戏辅助器”往昔... 大唐游戏辅助器是一款专注玩家量身打造的游戏记牌类型软件,在大唐游戏辅助器这款游戏中我们可以记录下每张...
三分钟了解“哈局辅助辅助”起初... 三分钟了解“哈局辅助辅助”起初有辅助开挂工具(讲解有挂);无需打开直接搜索加薇136704302(咨...
今日百科“微乐小程序黑科技免费... 今日百科“微乐小程序黑科技免费”从前有辅助插件(证实有挂);无需打开直接搜索加薇136704302(...
透视模拟器“情怀国粹麻将辅助器... >>您好:情怀国粹麻将辅助器确实是有挂的,很多玩家在这款情怀国粹麻将辅助器游戏中打牌都会发现很多用户...
实测教程“创游世界辅助器”原先... 实测教程“创游世界辅助器”原先有开挂辅助神器(有挂教学);亲,创游世界辅助器这款游戏原来确实可以开挂...
技巧知识分享“德普之星透视辅助... 技巧知识分享“德普之星透视辅助软件”本然有辅助平台(竟然有挂);无需打开直接搜索加(薇:136704...