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

相关内容

热门资讯

据统计!aapoker透视脚本... 据统计!aapoker透视脚本,德普之星私人局透视,都是真的是有挂(有挂分析)1、在德普之星私人局透...
为切实保障!德州透视hhpok... 为切实保障!德州透视hhpoker,德普之星辅助软件,都是真的是有挂(有挂辅助)一、德普之星辅助软件...
代打辅助挂!hh poker透... 代打辅助挂!hh poker透视器下载,德普之星透视辅助软件是真的吗,切实确实有挂(有挂方略)1)德...
黑科技辅助挂!wepoker辅... 黑科技辅助挂!wepoker辅助器有哪些功能,德扑之星辅助器怎么用,竟然确实有挂(有挂方略)1、任何...
有消息称!wepoker俱乐部... 有消息称!wepoker俱乐部辅助器,德普之星怎么开辅助,确实是真的有挂(有挂透视)进入游戏-大厅左...
现有说明如下!如何下载wpk透... 现有说明如下!如何下载wpk透视版,智星菠萝辅助,一直是有挂(有挂教学)1、这是跨平台的智星菠萝辅助...
目前!微扑克透视脚本,德普之星... 目前!微扑克透视脚本,德普之星透视辅助软件是真的吗,果然是真的有挂(有挂方法)1、很好的工具软件,可...
黑科技辅助!菠萝辅助器免费版的... 黑科技辅助!菠萝辅助器免费版的特点,德扑圈透视挂,果然真的是有挂(有挂方略)1、下载好德扑圈透视挂脚...
有了最新消息!德普之星透视辅助... 有了最新消息!德普之星透视辅助软件激活码,德普之星透视辅助,确实是有挂(有挂规律)一、德普之星透视辅...
一直以来!wepoker破解器... 一直以来!wepoker破解器,德普辅助软件,切实真的有挂(确实有挂)一直以来!wepoker破解器...