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

相关内容

热门资讯

黑科技好友房(pokermas... 黑科技好友房(pokermaster)轰趴大菠萝十三水起初是真的有挂!太嚣张了真是存在有挂(2021...
黑科技教程(wepokeai)... 黑科技教程(wepokeai)微扑克大厅最初真的有挂!太无语了真是是有挂(2020已更新)(哔哩哔哩...
黑科技数据(wpk辅助器)德州... 黑科技数据(wpk辅助器)德州aapoker俱乐部总是真的有挂!太坑了本然是有挂(2024已更新)(...
黑科技教程(微扑克机制)哈糖大... 黑科技教程(微扑克机制)哈糖大菠萝十三张素来存在有挂!太实锤了固有真的有挂(2023已更新)(哔哩哔...
黑科技辅助挂(来玩app)AA... 黑科技辅助挂(来玩app)AAPoker最初存在有挂!太实锤了原本真的有挂(2020已更新)(哔哩哔...
黑科技实锤(鱼扑克app ai... 1、黑科技实锤(鱼扑克app ai)德州微扑克原本是真的有挂!太无语了一贯是真的有挂(2023已更新...
黑科技玄学(Wepoke俱乐部... 黑科技玄学(Wepoke俱乐部)WepOke原来真的有挂!太离谱了总是是真的有挂(2026已更新)(...
黑科技实锤(约局吧)aapok... 黑科技实锤(约局吧)aapokER原本真的有挂!太实锤了素来是有挂(2022已更新)(哔哩哔哩)关于...
黑科技脚本(德扑之星带入)AA... 黑科技脚本(德扑之星带入)AAPOKER果然是真的有挂!太实锤了总是是真的有挂(2023已更新)(哔...
黑科技真的(德扑之星app)W... 黑科技真的(德扑之星app)WPk其实是有挂!太实锤了起初存在有挂(2023已更新)(哔哩哔哩);精...