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

相关内容

热门资讯

解密关于!斗棋有bug么开挂,... 解密关于!斗棋有bug么开挂,多乐小程序游戏破解器,详细工具(真实有挂)多乐小程序游戏破解器辅助器是...
必备科技!打哈儿辅助软件,八闽... 必备科技!打哈儿辅助软件,八闽辅助,详细方法(有挂功能)1、打哈儿辅助软件有没有辅助教程、打哈儿辅助...
推荐几款新版!皮皮游戏挂机辅助... 推荐几款新版!皮皮游戏挂机辅助,四川麻将口诀顺口溜,详细攻略(存在有挂)该软件可以轻松地帮助玩家将四...
一分钟揭秘!青龙辅助最新下载,... 一分钟揭秘!青龙辅助最新下载,悟空大厅微信辅助,详细脚本(有挂讲解)1、进入到悟空大厅微信辅助是否有...
一分钟了解!关春天凑一桌辅助,... 一分钟了解!关春天凑一桌辅助,山西扣点点辅助下载,详细神器(了解有挂)山西扣点点辅助下载透视方法中分...
必看攻略!边锋嘉兴辅助,皮皮游... 必看攻略!边锋嘉兴辅助,皮皮游戏辅助器,详细方法(有人有挂)运皮皮游戏辅助器辅助工具,进入游戏界面。...
大家学习交流!陕西三代辅助器免... 大家学习交流!陕西三代辅助器免费,光明大厅微信呢链接辅助试用,详细技巧(有挂教程)1、上手简单,内置...
玩家必看分享!微乐小程序辅助教... 玩家必看分享!微乐小程序辅助教程,哈灵脚本修改器,详细器(有挂透明挂)微乐小程序辅助教程破解侠是真的...
一秒答解!小松宿松游戏辅助,微... 一秒答解!小松宿松游戏辅助,微乐小程序微乐家乡辅助器,详细软件(有挂解惑);1、每一步都需要思考,不...
重大消息!科乐天天踢有没有挂作... 重大消息!科乐天天踢有没有挂作弊,老友地方内蒙古辅助,详细挂(有挂讲解)1、点击下载安装,科乐天天踢...