问题描述: 在Angular应用中,使用异步管道来加载图像源时,图像源的更新可能无效。
解决方法:
@Pipe({
name: 'asyncImage'
})
export class AsyncImagePipe implements PipeTransform {
transform(source: string | null): SafeUrl | null {
return source ? this.sanitizer.bypassSecurityTrustUrl(source) : null;
}
}
@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异步管道在图像源更新时无效的问题。具体使用哪一种方法取决于你的应用需求和具体情况。