2

I have an angular application on my own domain, that displays images from google storage like this:

<img src="googleUrl..."/>

The default Cache-Control is set to 3600 seconds which is way too low for me, because I want to cache the images for 1 week (the images on the storage change very rarely).

I tried to create an HttpInterceptor but it does not intercept the request that the src of the img makes.

I also tried to create a pipe and set a Cache-Control header but, the server being google, it gives me a Cross-Origin error. This is how I implemented it:

@Pipe({
    name: 'cacheResource',
})
export class CacheResourcePipe implements PipeTransform {
    constructor(private http: HttpClient, private sanitizer: DomSanitizer) {}
    transform(url): Observable<SafeUrl> {
        const headers = new HttpHeaders({
            'Cache-Control': 'public, max-age=2.592.000',
        });
        return this.http
            .get(url, {
                headers,
                responseType: 'blob',
            })
            .pipe(map((val) => URL.createObjectURL(val)));
    }
}

And then called like this:

<img [src]="'googleUrl.com' | cacheResource | async" />

(The pipe approach works with files stored on the same domain but I don't have this possibility)

Is there any way to achieve the long cache that I need without changing the server?

Mahdi Zarei
  • 5,644
  • 7
  • 24
  • 54
  • Is it possible to add images in local host and load image from local host first and if not found then go for http service. You can do this using pipe too – GRD Dec 10 '21 at 18:33
  • Im not quite sure i grasped the whole idea, if you could be a bit more clear i'd appriciate it. Thanks regardless, and i will try something similar to see if it works. – Alessandro Valentino Dec 10 '21 at 18:40
  • you can convert that blob into base64 string and then store it in local storage. https://stackoverflow.com/questions/6150289/how-can-i-convert-an-image-into-base64-string-using-javascript – Yogi Dec 11 '21 at 13:46

0 Answers0