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游戏真的是有挂的(详细透视辅助黑科技教程);wpk透视辅助...
4分钟总结!一起宁德钓蟹黑科技... 4分钟总结!一起宁德钓蟹黑科技,wpk代打是真的(详细透视辅助app教程);一起宁德钓蟹黑科技软件透...
5分钟了解!哥哥跑得快怎么赢,... 5分钟了解!哥哥跑得快怎么赢,约局互娱辅助(详细透视辅助神器教程)关于哥哥跑得快怎么赢机制的,其中提...
2分钟方法!开心游戏跑得快有挂... 2分钟方法!开心游戏跑得快有挂吗,传奇扑克辅助(详细透视辅助助手教程);一、开心游戏跑得快有挂吗有挂...
2分钟教学!福建天天开心辅助工... 2分钟教学!福建天天开心辅助工具,wepoke软件收费(详细透视辅助app教程)1、每一步都需要思考...
2分钟教程!腾讯广东麻将助赢神... 2分钟教程!腾讯广东麻将助赢神器,nzt德州辅助软件(详细透视辅助黑科技教程);腾讯广东麻将助赢神器...
七分钟辅助挂!哈局十三张怎么赢... 七分钟辅助挂!哈局十三张怎么赢,德扑之星可以看底牌(详细透视辅助插件教程)相信很多朋友都在电脑上玩过...
5分钟技巧!传送屋激k有挂吗,... 传送屋激k有挂吗新手教程相关信息汇总(需添加指定薇757446909获取下载链接);5分钟技巧!传送...
三分钟教程!钱塘十三水有挂是真... 三分钟教程!钱塘十三水有挂是真的吗,wpk线上实战(详细透视辅助app教程)1、很好的工具软件,可以...