Last active
February 21, 2024 11:13
-
-
Save ozexpert/d95677e1fe044e6173ef59840c9c484e to your computer and use it in GitHub Desktop.
AngularJS2 / Ionic2 : ImageCache Directive to use with imgcache.js
This file contains 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 { Directive, ElementRef, Input } from '@angular/core'; | |
declare var ImgCache: any; | |
@Directive({ | |
selector: '[image-cache]' | |
}) | |
export class ImageCacheDirective { | |
constructor ( | |
private el: ElementRef | |
) { | |
// init | |
} | |
ngOnInit() { | |
this.el.nativeElement.crossOrigin = "Anonymous"; // CORS enabling | |
ImgCache.isCached(this.el.nativeElement.src, (path: string, success: any) => { | |
console.log('path - '+ path); | |
console.log('success - '+ success); | |
if (success) { | |
// already cached | |
console.log('already cached so using cached'); | |
ImgCache.useCachedFile(this.el.nativeElement); | |
} else { | |
// not there, need to cache the image | |
console.log('not there, need to cache the image - ' + this.el.nativeElement.src); | |
ImgCache.cacheFile(this.el.nativeElement.src, () => { | |
console.log('cached file'); | |
// ImgCache.useCachedFile(el.nativeElement); | |
}); | |
} | |
}); | |
} | |
} |
Create a file called declarations.d.ts file and inside this add
declare module 'imgcache.js';
Then in your component add
import ImgCache from 'imgcache.js';
Sorry if you've already done this, I got a hunch you might have not.
hi thanks for this code
how to use this code on api call ? not problem ?
Cross-origin error :-(
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I had the same problem as @ChristianBruno.
I tried adding imgcache.js with:
npm install imgcache.js --save
Then instead of:
import ImgCache from 'imgcache.js';
I used
import ImgCache from 'imgcache.js';
Now the application runs, but the cache feature doesn't work :-(
I have an dynamic image which is generated with timestamp inside it, in order to check the cache (with php
imagecreate
).If I add a delay (
sleep(10)
for example), the image in not shown till the delay is finished.And if I remove the image from server, I get a broken-image-url symbol...
Some helpful information:
In ImageCacheDirective I added a
concole.log
message on the beginning of ngOnInit. I get to see it.However, the log messages on the beginning of the
ImgCache.isCached
callback are not shown - callback is not called.