Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Caching Images in Angular

I am having around 300 designs and I am loading all at a time. I would like to cache those images instead of calling server everytime. (My desings won't change most of the time). Below is the code, of how I am loading them. What would be the best approach to cache them.

app-thumbnail is a different component where I am only loading image.

 <div *ngFor="let design of designs">
      <div (click)="showDesignDetails(design.designId)">
          <app-thumbnail [designId]="design.designId"></app-thumbnail>          
      </div>
    </div>
like image 801
Chatra Avatar asked May 31 '19 02:05

Chatra


People also ask

How do I cache a HTTP request in angular?

By the end of this post, you'll be able to cache your http request like this: Load data from the localstorage. A custom http-client service: This service will use the angular HttpClient under the hood, but will also use the cache service mentioned above to get and save data from/to localstorage.

How do I change the path of the cache in angular?

For more information, see environment in cache options. The Angular CLI checks for the presence and value of the CI environment variable to determine in which environment it is running. By default, .angular/cache is used as a base directory to store cache results. To change this path to .cache/ng, run the following command:

How to load images in angular?

This tutorial shows multiple examples in Angular, One example is to load images using the img tag Another example is to bind the src attribute to the assets folder. Normally, Images are placed in the src/assets folder in the Angular application. src |__assets |__images |__first.png |__app |__app.component.html

How to cache the httpclient observables in angular?

Instead of caching the return values from the server, we can cache the observables that the Angular HttpClient service returns. This way, both function calling and caching will be synchronous. The only trick is that we must use the shareReplay operator that will allow the subscribers to view the result of the HTTP call.


1 Answers

I can think of two ways:

1) Application Cache Manifest. According to the documentation,

Developers can use the Application Cache (AppCache) interface to specify resources that the browser should cache and make available to offline users. Applications that are cached load and work correctly even if users click the refresh button when they are offline.

2) Service Workers. Through the use of service workers, you can cache various types of resources, including images and network requests.

Though this brings me to the topic of using Progressive Web Applications (PWA). Since you are using Angular, you can easily set it up as a PWA (which is based on the usage of service workers) by following the official Angular guide for setting up service workers.

like image 90
wentjun Avatar answered Sep 17 '22 11:09

wentjun