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

相关内容

热门资讯

截至发稿!约局吧德州可以透视吗... 截至发稿!约局吧德州可以透视吗(透视)神兽互娱辅助免费(切实是有辅助插件)-哔哩哔哩1、操作简单,无...
现场直击!hhpoker万能辅... 现场直击!hhpoker万能辅助器(透视)新天道破解版(都是有辅助工具)-哔哩哔哩1、让任何用户在无...
透视app!wepoker轻量... 透视app!wepoker轻量版透视系统(透视)四川微乐微信麻将小程序辅助(好像存在有辅助辅助器)-...
透视好牌!wpk透视是真的吗(... 透视好牌!wpk透视是真的吗(透视)福建大玩家辅助器(其实是有辅助app)-哔哩哔哩在进入福建大玩家...
透视透视!wpk软件是真的吗(... 透视透视!wpk软件是真的吗(透视)微乐四川麻将辅助器(本来是有辅助安装)-哔哩哔哩1、微乐四川麻将...
透视攻略!wpk辅助购买(透视... 透视攻略!wpk辅助购买(透视)新玄龙开挂图片(其实是真的辅助修改器)-哔哩哔哩1、完成新玄龙开挂图...
透视软件!大菠萝手游辅助(透视... 透视软件!大菠萝手游辅助(透视)微信小程序微乐辅助器(竟然存在有辅助平台)-哔哩哔哩1、进入游戏-大...
据玩家消息!wpk透视插件(透... 据玩家消息!wpk透视插件(透视)广西老友玩有破解(总是存在有辅助插件)-哔哩哔哩1、完成广西老友玩...
透视攻略!wepoker透视脚... 透视攻略!wepoker透视脚本网页(透视)麻将外卦软件框架模式(果然有辅助平台)-哔哩哔哩1、首先...
截至目前!拱趴大菠萝怎么开挂(... 截至目前!拱趴大菠萝怎么开挂(透视)桂麻圈破解版ios(真是有辅助神器)-哔哩哔哩1、实时桂麻圈破解...