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

相关内容

热门资讯

两分钟开挂!广西友乐辅助器,微... 两分钟开挂!广西友乐辅助器,微信海盗来了辅助工具,透明挂教程-2026最新版本进入游戏-大厅左侧-新...
据玩家消息!点星休闲辅助器下载... 据玩家消息!点星休闲辅助器下载(辅助挂)其实有挂(有挂讲义)-哔哩哔哩 【无需打开直接搜索加薇136...
为了进一步!陕麻圈辅助器购买(... 为了进一步!陕麻圈辅助器购买(辅助挂)其实有挂(有挂阶段)-哔哩哔哩;打开点击测试直接进入微信(13...
四分钟开挂!中至上饶打炸辅助器... 四分钟开挂!中至上饶打炸辅助器开挂,广丰510k辅助,必备教程-2026最新版本1、完成中至上饶打炸...
此事备受玩家关注!摸一把花牌辅... 此事备受玩家关注!摸一把花牌辅助(辅助挂)一贯是有挂的(有挂模板)-哔哩哔哩 >>您好:软件加薇13...
2分钟开挂!微信公众号辅助工具... 2分钟开挂!微信公众号辅助工具,海贝之城辅助器,详细教程-2026最新版本1)微信公众号辅助工具辅助...
据统计!途游辅助软件(辅助挂)... 据统计!途游辅助软件(辅助挂)一直真的有挂(有挂方针)-哔哩哔哩>>您好:软件加薇136704302...
六分钟开挂!518互游辅助器免... 六分钟开挂!518互游辅助器免费下载,微信开心泉州辅助,大神讲解-2026最新版本1、点击下载安装,...
有消息称!新道游app辅助器(... 您好:这款新道游app辅助器游戏是可以开挂的,确实是有挂的,很多玩家在这款新道游app辅助器游戏中打...
第8分钟开挂!陕西三代实战技巧... 第8分钟开挂!陕西三代实战技巧,点星休闲修改,普及教程-2026最新版本陕西三代实战技巧辅助器中分为...