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

相关内容

热门资讯

今日头条外挂!王者众娱外挂多功... 今日头条外挂!王者众娱外挂多功能AI插件,王者众娱竟然存在有外挂插件进入游戏-大厅左侧-新手福利-激...
必备科技作弊器!淮滨互娱作弊器... 必备科技作弊器!淮滨互娱作弊器多功能AI工具,淮滨互娱真是真的是有作弊器工具1、进入到淮滨互娱是否有...
我来分享作弊器!本地互娱作弊器... 我来分享作弊器!本地互娱作弊器多功能AI技巧,本地互娱本来是有作弊器技巧本地互娱透视方法中分为三种模...
终于懂了作弊器!众享互娱作弊器... 终于懂了作弊器!众享互娱作弊器多功能AI方法,众享互娱好像存在有作弊器方法运众享互娱辅助工具,进入游...
带你了解透视挂!葫芦娃大厅透视... 带你了解透视挂!葫芦娃大厅透视挂多功能AIapp,葫芦娃大厅好像存在有透视挂app1、该软件可以轻松...
让我来分享经验透视挂!欢盈娱乐... 让我来分享经验透视挂!欢盈娱乐透视挂多功能AI软件,欢盈娱乐本来真的有透视挂软件1、玩家可以在欢盈娱...
技术分享辅助器!海象互娱辅助器... 技术分享辅助器!海象互娱辅助器多功能AI工具,海象互娱好像有辅助器工具1、下载好海象互娱脚本下载之后...
科普攻略辅助!福城娱乐辅助多功... 科普攻略辅助!福城娱乐辅助多功能AI插件,福城娱乐真是存在有辅助插件1、福城娱乐破解器简单,福城娱乐...
查到实测开挂!红月大厅开挂多功... 查到实测开挂!红月大厅开挂多功能AI方法,红月大厅确实是真的有开挂方法1、玩家可以在红月大厅透视最简...
发现一款透视挂!旺牛娱乐透视挂... 发现一款透视挂!旺牛娱乐透视挂多功能AIapp,旺牛娱乐确实是有透视挂app1、点击下载安装,旺牛娱...