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

相关内容

热门资讯

黑科技攻略(Wepoke开挂)... 黑科技攻略(Wepoke开挂)外挂透明挂辅助ai代打(黑科技ai)其实是真的有挂(有挂讲解)-哔哩哔...
黑科技有挂(aapoker辅助... 黑科技有挂(aapoker辅助)外挂透明挂辅助挂(透明挂黑科技)都是是有挂(有挂方式)-哔哩哔哩1、...
黑科技好牌(wpk机制)外挂透... 黑科技好牌(wpk机制)外挂透明挂辅助下载(透明挂黑科技)一直是真的有挂(有挂秘籍)-哔哩哔哩;1、...
黑科技教学(德州ai智能)外挂... 黑科技教学(德州ai智能)外挂透明挂辅助代打(透明挂黑科技)都是是有挂(确实有挂)-哔哩哔哩该软件可...
黑科技黑科技(众合推扑克)外挂... 黑科技黑科技(众合推扑克)外挂透明挂辅助神器(透明黑科技)确实真的有挂(今日头条)-哔哩哔哩众合推扑...
黑科技辅助(wpk辅助器)外挂... 黑科技辅助(wpk辅助器)外挂透明挂辅助代打(ai辅助)确实是真的有挂(有挂细节)-哔哩哔哩1、wp...
黑科技挂(aapker代理)外... 黑科技挂(aapker代理)外挂透明挂辅助挂(智能ai)好像是真的有挂(了解有挂)-哔哩哔哩1、构建...
黑科技神器(云扑克德州)外挂透... 黑科技神器(云扑克德州)外挂透明挂辅助AI(辅助挂)都是有挂(真的有挂)-哔哩哔哩1、黑科技神器(云...
黑科技模拟器(Wepoke教学... 黑科技模拟器(Wepoke教学)外挂透明挂辅助黑科技(透明挂黑科技)竟然真的是有挂(有挂细节)-哔哩...
黑科技工具(WPK存在)外挂透... 黑科技工具(WPK存在)外挂透明挂辅助设备(透明挂黑科技)竟然是真的有挂(有挂秘籍)-哔哩哔哩1、W...