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

相关内容

热门资讯

一分钟了解!闲闲辅助器(辅助挂... 一分钟了解!闲闲辅助器(辅助挂)wepoker透视脚本免费下载(一贯是真的有挂);相信小伙伴都知道这...
分享给玩家!黑科技辅助器软件(... 分享给玩家!黑科技辅助器软件(辅助挂)wepoker底牌透视脚本(素来是有挂)是一款可以让一直输的玩...
一分钟揭秘!新超凡软甲辅助(辅... 一分钟揭秘!新超凡软甲辅助(辅助挂)wepoker亲友圈有用吗(素来真的是有挂);详细新超凡软甲辅助...
免费测试版!微乐广西麻辣辅助(... 免费测试版!微乐广西麻辣辅助(辅助挂)wepoker有辅助功能吗(切实是真的有挂);1.微乐广西麻辣...
教程攻略!广东雀神智能插件辅助... 教程攻略!广东雀神智能插件辅助脚本(辅助挂)wepokerplus脚本(从前存在有挂);广东雀神智能...
分享一款!老友广东麻将有挂吗(... 分享一款!老友广东麻将有挂吗(辅助挂)werplan脚本(一贯真的是有挂);老友广东麻将有挂吗软件透...
带你了解!陕西微乐小程序辅助(... 带你了解!陕西微乐小程序辅助(辅助挂)wepoker有插件吗(往昔是有挂)相信很多朋友都在电脑上玩过...
一分钟了解!吉祥填大坑小程序辅... 一分钟了解!吉祥填大坑小程序辅助(辅助挂)wepoker游戏下载(果然真的是有挂);1、很好的吉祥填...
终于清楚!广东闲来app辅助(... 终于清楚!广东闲来app辅助(辅助挂)wpk透视工作室(原先是真的有挂);广东闲来app辅助免费下载...
科普!手机奇迹辅助工具(辅助挂... 科普!手机奇迹辅助工具(辅助挂)wepoker开脚本视频(素来真的有挂)是一款可以让一直输的玩家,快...