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

相关内容

热门资讯

透视好牌!如何下载德普之星辅助... 透视好牌!如何下载德普之星辅助软件(透视)辅助软件(竟然真的是有挂);一、如何下载德普之星辅助软件软...
透视辅助!aa poker辅助... 透视辅助!aa poker辅助(透视)透视脚本(果然真的是有挂)1、金币登录送、破产送、升级送、活动...
透视免费!德普之星app安卓版... 透视免费!德普之星app安卓版破解版(透视)辅助软件(好像是有挂);德普之星app安卓版破解版辅助器...
透视脚本!aapoker怎么设... 透视脚本!aapoker怎么设置提高好牌几率(透视)脚本(确实真的有挂)亲,关键说明,aapoker...
透视软件!德普之星透视辅助软件... 透视软件!德普之星透视辅助软件是真的吗(透视)透视辅助软件(确实真的有挂);小薇(透视辅助)致您一封...
透视线上!aapoker公共底... 透视线上!aapoker公共底牌(透视)透视脚本入口(确实是真的有挂)1、该软件可以轻松地帮助玩家将...
透视了解!德扑圈透视(透视)透... 透视了解!德扑圈透视(透视)透视辅助软件(真是真的有挂)进入游戏-大厅左侧-新手福利-激活码辅助透视...
透视游戏!aapoker破解侠... 透视游戏!aapoker破解侠是真的吗(透视)透视方法(都是真的有挂)亲,关键说明,aapoker破...
透视透视!德扑之心免费透视(透... 透视透视!德扑之心免费透视(透视)透视免费(其实是真的有挂);1、德扑之心免费透视透视辅助简单,德扑...
透视智能ai!aapoker怎... 透视智能ai!aapoker怎么选牌(透视)插件(竟然存在有挂)1、进入游戏-大厅左侧-新手福利-激...