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、下载好拱趴大菠萝技巧透视辅助下载之后点击...
普及知识!七千在线辅助,微乐广... 普及知识!七千在线辅助,微乐广西麻辣(确实存在有挂)1、任何微乐广西麻辣透视是真的假的的玩家都可以机...
技术分享!边锋小程序辅助免费,... 技术分享!边锋小程序辅助免费,广西老友玩有破解(本来是真的有挂)1、玩家可以在边锋小程序辅助免费透视...
推荐十款!对战互娱辅助,微信小... 推荐十款!对战互娱辅助,微信小程序辅助器免费(一贯存在有挂)1、操作简单,无需微信小程序辅助器免费手...
重大推荐!卡五星游戏源码,填大... 重大推荐!卡五星游戏源码,填大坑辅助器视频(本来真的是有挂)1、任何填大坑辅助器视频透视是真的假的的...
普及知识!老友跑得快辅助小说最... 普及知识!老友跑得快辅助小说最新章节,hhpoker免费辅助器(竟然存在有挂)老友跑得快辅助小说最新...
分享一款!欢乐联盟卡五星辅助,... 分享一款!欢乐联盟卡五星辅助,广西优乐免费辅助(真是有挂)该软件可以轻松地帮助玩家将欢乐联盟卡五星辅...
必看攻略!四川皮皮辅助,h5大... 必看攻略!四川皮皮辅助,h5大厅反杀(果然真的是有挂)1、完成四川皮皮辅助有辅助插件,帮助玩家取得所...
程序员教你!微乐小程序辅助开发... 程序员教你!微乐小程序辅助开发透视,手机微乐小程序游戏破解器(确实真的有挂)1、手机微乐小程序游戏破...
盘点一款!789大菠萝攻略,吉... 盘点一款!789大菠萝攻略,吉祥填大坑辅助器攻略(切实是有挂)1)吉祥填大坑辅助器攻略辅助插件:进一...