-
-
Save jogboms/a2b69d85b7e49c555ae69fe26e39eb27 to your computer and use it in GitHub Desktop.
ImageCache pipe for NativeScript-Angular
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Pipe, PipeTransform, NgZone } from '@angular/core'; | |
import { Observable } from 'rxjs/Observable'; | |
import { ImageSource, fromResource } from 'image-source'; | |
import { Cache } from 'ui/image-cache'; | |
import { isFileOrResourcePath, isDataURI } from 'utils/utils'; | |
let cache = new Cache(); | |
cache.placeholder = fromResource('placeholder'); | |
cache.enableDownload(); | |
/** | |
* Use: | |
* <Image src="'http://image.url.at.domain.tld/sub/path.jpg' | imageCache | async"></Image> | |
*/ | |
@Pipe({ | |
name: 'imageCache' | |
}) | |
export class ImageCachePipe implements PipeTransform { | |
constructor(private ngZone: NgZone) { | |
} | |
transform(imageUrl: string, usePlaceholder = true): Observable<ImageSource | string> { | |
if (isFileOrResourcePath(imageUrl) || isDataURI(imageUrl)) { | |
return Observable.of(imageUrl); | |
} | |
let image = cache.get(imageUrl); | |
if (image) { | |
return Observable.of(image); | |
} | |
return Observable | |
.create((observer) => { | |
if (cache.placeholder && usePlaceholder) { | |
observer.next(cache.placeholder); | |
} | |
cache.push({ | |
key: imageUrl, | |
url: imageUrl, | |
completed: (image: any, key: string) => { | |
if (key === imageUrl) { | |
this.ngZone.run(() => { | |
observer.next(image); | |
observer.complete(); | |
}); | |
} | |
}, | |
}); | |
}); | |
} | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment