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

相关内容

热门资讯

黑科技脚本(WEPOke)软件... 黑科技脚本(WEPOke)软件免费版(黑科技)软件透明演示(都是是有挂)1、在ai机器人技巧中,中转...
透视代打(wPk)后台管理系统... 透视代打(wPk)后台管理系统(黑科技)透明挂(总是有挂);致您一封信;亲爱玩家:《透明挂》新活动版...
大神辅助(微扑克)辅助测试(辅... 自定义系统规律,只需要输入自己想要的开挂功能,一键便可以生成出微扑克专用辅助器,不管你是想分享给你好...
玩家辅助(微扑克)系统发牌逻辑... 玩家辅助(微扑克)系统发牌逻辑(辅助挂)辅助(确实是真的有挂)1、不需要AI权限,帮助你快速的进行计...
黑科技苹果版(wePOke)有... 黑科技苹果版(wePOke)有没有挂(黑科技)透明黑科技(其实是真的有挂)1、ai机器人多个强度级别...
黑科技辅助(微扑克)辅助工具怎... 黑科技辅助(微扑克)辅助工具怎么下载(辅助挂)辅助器免费版(真是真的有挂)1、这是跨平台的黑科技,在...
黑科技安装(wepokE)辅助... 黑科技安装(wepokE)辅助软件下载链接(黑科技)辅助器真的有效果(真是真的有挂)1、在ai机器人...
可靠辅助(微扑克)ai算牌器(... 可靠辅助(微扑克)ai算牌器(辅助挂)ai胜率(原来真的是有挂)1、很好的工具软件,可以解锁游戏的a...
黑科技教程(wepower)软... 黑科技教程(wepower)软件免费版(黑科技)ai代打(总是真的是有挂)1、ai辅助优化,发牌逻辑...
可靠辅助(微扑克)ai胜率(辅... 可靠辅助(微扑克)ai胜率(辅助挂)ai代打(真是是真的有挂)您好,,确实是有挂的,很多玩家在这款游...