{"id":13807084,"url":"https://github.com/nigrosimone/ng-http-caching","last_synced_at":"2025-04-06T03:07:17.173Z","repository":{"id":55760996,"uuid":"285511120","full_name":"nigrosimone/ng-http-caching","owner":"nigrosimone","description":"Cache for HTTP requests in Angular application.","archived":false,"fork":false,"pushed_at":"2025-01-12T15:44:43.000Z","size":2851,"stargazers_count":49,"open_issues_count":0,"forks_count":5,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-03-29T07:01:44.526Z","etag":null,"topics":["angular","angular2","cache"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/ng-http-caching","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/nigrosimone.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"open_collective":"simone-nigro"}},"created_at":"2020-08-06T08:03:18.000Z","updated_at":"2025-02-21T08:05:56.000Z","dependencies_parsed_at":"2023-11-12T14:43:56.148Z","dependency_job_id":"fbd4ddb7-51e9-4e6d-933f-9dac14b7a85f","html_url":"https://github.com/nigrosimone/ng-http-caching","commit_stats":{"total_commits":281,"total_committers":1,"mean_commits":281.0,"dds":0.0,"last_synced_commit":"986343d80e43bf00ddc9cee437b89c3c8826c01f"},"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nigrosimone%2Fng-http-caching","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nigrosimone%2Fng-http-caching/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nigrosimone%2Fng-http-caching/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nigrosimone%2Fng-http-caching/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/nigrosimone","download_url":"https://codeload.github.com/nigrosimone/ng-http-caching/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247427006,"owners_count":20937201,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["angular","angular2","cache"],"created_at":"2024-08-04T01:01:20.585Z","updated_at":"2025-04-06T03:07:17.152Z","avatar_url":"https://github.com/nigrosimone.png","language":"TypeScript","funding_links":["https://opencollective.com/simone-nigro","https://www.paypal.com/paypalme/snwp"],"categories":["Architecture and Advanced Topics"],"sub_categories":["HTTP"],"readme":"# NgHttpCaching [![Build Status](https://travis-ci.org/nigrosimone/ng-http-caching.svg?branch=master)](https://travis-ci.com/github/nigrosimone/ng-http-caching) [![Coverage Status](https://coveralls.io/repos/github/nigrosimone/ng-http-caching/badge.svg?branch=master)](https://coveralls.io/github/nigrosimone/ng-http-caching?branch=master) [![NPM version](https://img.shields.io/npm/v/ng-http-caching.svg)](https://www.npmjs.com/package/ng-http-caching)\n\nCache for HTTP requests in Angular application.\n\n## Description\n\nSometime there is a need to cache the HTTP requests so that browser doesn’t have to hit server to fetch same data when same service is invoked serially or in parallel. `NgHttpCaching` intercept all request are made, try to retrieve a cached instance of the response and then return the cached response or send the request to the backend. Once the operation has completed cache the response.\n\nSee the [stackblitz demo](https://stackblitz.com/edit/demo-ng-http-caching?file=src%2Fapp%2Fapp.component.ts).\n\n## Features\n\n✅ HTTP caching\u003cbr\u003e\n✅ Handles simultaneous/parallel requests\u003cbr\u003e\n✅ Automatic garbage collector of cache\u003cbr\u003e\n✅ More than 90% unit tested\u003cbr\u003e\n✅ LocalStorage, SessionStorage, MemoryStorage and custom cache storage\u003cbr\u003e\n✅ Check response headers cache-control and expires\u003cbr\u003e\n\n## Get Started\n\n*Step 1*: install `ng-http-caching`\n\n```bash\nnpm i ng-http-caching\n```\n\n*Step 2*: Provide `NgHttpCaching` into your `bootstrapApplication`, eg.:\n\n```ts\nimport { bootstrapApplication } from '@angular/platform-browser';\nimport { provideHttpClient, withInterceptorsFromDi } from '@angular/common/http';\nimport { AppComponent } from './app.component';\nimport { provideNgHttpCaching } from 'ng-http-caching';\n\nbootstrapApplication(AppComponent, {\n  providers: [\n    provideNgHttpCaching(),\n    provideHttpClient(withInterceptorsFromDi())\n  ]\n});\n```\n\nif you want configure `ng-http-caching`, you can pass a configuration, eg.:\n\n```ts\nimport { bootstrapApplication } from '@angular/platform-browser';\nimport { provideHttpClient, withInterceptorsFromDi } from '@angular/common/http';\nimport { AppComponent } from './app.component';\nimport { provideNgHttpCaching, NgHttpCachingConfig } from 'ng-http-caching';\n\n// your config...\nconst ngHttpCachingConfig: NgHttpCachingConfig = {\n  lifetime: 1000 * 10 // cache expire after 10 seconds\n};\n\nbootstrapApplication(AppComponent, {\n  providers: [\n    provideNgHttpCaching(ngHttpCachingConfig),\n    provideHttpClient(withInterceptorsFromDi())\n  ]\n});\n```\n\n## Config\n\nThis is all the configuration interface, see below for the detail of each config.\n\n```ts\n// all configuration are optionally\nexport interface NgHttpCachingConfig {\n  version?: string;\n  lifetime?: number;\n  allowedMethod?: string[];\n  cacheStrategy?: NgHttpCachingStrategy;\n  store?: NgHttpCachingStorageInterface;\n  isExpired?: (entry: NgHttpCachingEntry) =\u003e boolean | undefined | void;\n  isValid?: (entry: NgHttpCachingEntry) =\u003e boolean | undefined | void;\n  isCacheable?: (req: HttpRequest\u003cany\u003e) =\u003e boolean | undefined | void;\n  getKey?: (req: HttpRequest\u003cany\u003e) =\u003e string | undefined | void;\n}\n```\n\n### version (string - default: VERSION.major)\nCache version. When you have a breaking change, change the version, and it'll delete the current cache automatically.\nThe default value is Angular major version (eg. 13), in this way, the cache is invalidated on every Angular upgrade.\n\n### lifetime (number - default: 3.600.000)\nNumber of millisecond that a response is stored in the cache. \nYou can set specific \"lifetime\" for each request by add the header `X-NG-HTTP-CACHING-LIFETIME` (see example below).\n\n### checkResponseHeaders (boolean - default false);\nIf true response headers cache-control and expires are respected.\n\n### allowedMethod (string[] - default: ['GET', 'HEAD'])\nArray of allowed HTTP methods to cache. \nYou can allow multiple methods, eg.: `['GET', 'POST', 'PUT', 'DELETE', 'HEAD']` or \nallow all methods by: `['ALL']`. If `allowedMethod` is an empty array (`[]`), no response are cached.\n*Warning!* `NgHttpCaching` use the full url (url with query parameters) as unique key for the cached response,\nthis is correct for the `GET` request but is _potentially_ wrong for other type of request (eg. `POST`, `PUT`). \nYou can set a different \"key\" by customizing the `getKey` config method (see `getKey` section).\n\n### cacheStrategy (enum NgHttpCachingStrategy - default: NgHttpCachingStrategy.ALLOW_ALL)\nSet the cache strategy, possible strategies are:\n- `NgHttpCachingStrategy.ALLOW_ALL`: All request are cacheable if HTTP method is into `allowedMethod`;\n- `NgHttpCachingStrategy.DISALLOW_ALL`: Only the request with `X-NG-HTTP-CACHING-ALLOW-CACHE` header are cacheable if HTTP method is into `allowedMethod`;\n\n### store (class of NgHttpCachingStorageInterface - default: NgHttpCachingMemoryStorage)\nSet the cache store. You can implement your custom store by implement the `NgHttpCachingStorageInterface` interface, eg.:\n\n```ts\nimport { NgHttpCachingConfig, NgHttpCachingStorageInterface } from 'ng-http-caching';\n\nclass MyCustomStore implements NgHttpCachingStorageInterface {\n  // ... your logic\n}\n\nconst ngHttpCachingConfig: NgHttpCachingConfig = {\n  store: new MyCustomStore(),\n};\n```\n\nthere is also a `withNgHttpCachingLocalStorage` a cache store with persistence into `localStorage`:\n\n```ts\nimport { NgHttpCachingConfig, withNgHttpCachingLocalStorage } from 'ng-http-caching';\n\nconst ngHttpCachingConfig: NgHttpCachingConfig = {\n  store: withNgHttpCachingLocalStorage(),\n};\n```\n\nand a `withNgHttpCachingSessionStorage` a cache store with persistence into `sessionStorage`:\n\n```ts\nimport { NgHttpCachingConfig, withNgHttpCachingSessionStorage } from 'ng-http-caching';\n\nconst ngHttpCachingConfig: NgHttpCachingConfig = {\n  store: withNgHttpCachingSessionStorage(),\n};\n```\n\n### isExpired (function - default see NgHttpCachingService.isExpired());\nIf this function return `true` the request is expired and a new request is send to backend, if return `false` isn't expired. \nIf the result is `undefined`, the normal behaviour is provided.\nExample of customization:\n\n```ts\nimport { NgHttpCachingConfig, NgHttpCachingEntry } from 'ng-http-caching';\n\nconst ngHttpCachingConfig: NgHttpCachingConfig = {\n  isExpired: (entry: NgHttpCachingEntry): boolean | undefined =\u003e {\n      // In this example a special API endpoint (/my-endpoint) send into the body response\n      // an expireAt Date property. Only for this endpoint the expiration is provided by expireAt value.\n      // For all the other endpoint normal behaviour is provided.\n      if( entry.request.urlWithParams.indexOf('/my-endpoint') !== -1 ){\n        return entry.response.body.expireAt.getTime() \u003e Date.now();\n      }\n      // by returning \"undefined\" normal \"ng-http-caching\" workflow is applied\n      return undefined;\n    },\n};\n```\n\n### isValid (function - default see NgHttpCachingService.isValid());\nIf this function return `true` the cache entry is valid and can be stored, if return `false` isn't valid. \nIf the result is `undefined`, the normal behaviour is provided.\nDefault behaviour is whether the status code falls in the 2xx range and response headers cache-control and expires allow cache.\nExample of customization:\n\n```ts\nimport { NgHttpCachingConfig, NgHttpCachingEntry } from 'ng-http-caching';\n\nconst ngHttpCachingConfig: NgHttpCachingConfig = {\n  isValid: (entry: NgHttpCachingEntry): boolean | undefined =\u003e {\n      // In this example only response with status code 200 can be stored into the cache\n      return entry.response.status === 200;\n    },\n};\n```\n\n### isCacheable (function - default see NgHttpCachingService.isCacheable());\nIf this function return `true` the request is cacheable, if return `false` isn't cacheable. \nIf the result is `undefined`, the normal behaviour is provided.\nExample of customization:\n\n```ts\nimport { NgHttpCachingConfig } from 'ng-http-caching';\n\nconst ngHttpCachingConfig: NgHttpCachingConfig = {\n  isCacheable: (req: HttpRequest\u003cany\u003e): boolean | undefined =\u003e {\n      // In this example the /my-endpoint isn't cacheable.\n      // For all the other endpoint normal behaviour is provided.\n      if( req.urlWithParams.indexOf('/my-endpoint') !== -1 ){\n        return false;\n      }\n      // by returning \"undefined\" normal \"ng-http-caching\" workflow is applied\n      return undefined;\n    },\n};\n```\n\n\n### getKey (function - default see NgHttpCachingService.getKey());\nThis function return the unique key (`string`) for store the response into the cache. \nIf the result is `undefined`, the normal behaviour is provided.\nExample of customization:\n\n```ts\nimport { NgHttpCachingConfig } from 'ng-http-caching';\nimport * as hash from 'object-hash';  // install object-hash with: npm i object-hash\n\nconst hashOptions = {\n  algorithm: 'md5',\n  encoding: 'hex'\n};\n\nconst ngHttpCachingConfig: NgHttpCachingConfig = {\n  allowedMethod: ['GET', 'POST', 'PUT', 'DELETE', 'HEAD'],\n  getKey: (req: HttpRequest\u003cany\u003e): string | undefined =\u003e {\n    // In this example the full request is hashed for provide an unique key for the cache.\n    // This is important if you want support method like POST or PUT.\n    return req.method + '@' + req.urlWithParams + '@' + hash(req.params, hashOptions) + '@' + hash(req.body, hashOptions);\n  },\n};\n```\n\n## Headers\n\n`NgHttpCaching` use some custom headers for customize the caching behaviour.\nThe supported headers are exported from the enum `NgHttpCachingHeaders`:\n\n```ts\nexport enum NgHttpCachingHeaders {\n  ALLOW_CACHE = 'X-NG-HTTP-CACHING-ALLOW-CACHE',\n  DISALLOW_CACHE = 'X-NG-HTTP-CACHING-DISALLOW-CACHE',\n  LIFETIME = 'X-NG-HTTP-CACHING-LIFETIME',\n  TAG = 'X-NG-HTTP-CACHING-TAG',\n}\n```\n\nAll those headers are removed before send the request to the backend.\n\n### X-NG-HTTP-CACHING-ALLOW-CACHE (string: any value);\n\nIf you have choose the `DISALLOW_ALL` cache strategy, you can mark specific request as cacheable by adding the header `X-NG-HTTP-CACHING-ALLOW-CACHE`, eg.:\n\n```ts\nthis.http.get('https://my-json-server.typicode.com/typicode/demo/db', {\n  headers: {\n    [NgHttpCachingHeaders.ALLOW_CACHE]: '1',\n  }\n}).subscribe(e =\u003e console.log);\n```\n\n### X-NG-HTTP-CACHING-DISALLOW-CACHE (string: any value);\n\nYou can disallow specific request by add the header `X-NG-HTTP-CACHING-DISALLOW-CACHE`, eg.:\n\n```ts\nthis.http.get('https://my-json-server.typicode.com/typicode/demo/db', {\n  headers: { \n    [NgHttpCachingHeaders.DISALLOW_CACHE]: '1',\n  }\n}).subscribe(e =\u003e console.log);\n```\n\n### X-NG-HTTP-CACHING-LIFETIME (string: number of millisecond);\n\nYou can set specific lifetime for request by add the header `X-NG-HTTP-CACHING-LIFETIME` with a string value as the number of millisecond, eg.:\n\n```ts\nthis.http.get('https://my-json-server.typicode.com/typicode/demo/db', {\n  headers: {\n    [NgHttpCachingHeaders.LIFETIME]: (1000 * 60 * 60 * 24 * 365).toString(), // one year\n  }\n}).subscribe(e =\u003e console.log);\n```\n\n### X-NG-HTTP-CACHING-TAG (string: tag name);\n\nYou can tag multiple request by adding special header `X-NG-HTTP-CACHING-TAG` with the same tag and \nusing `NgHttpCachingService.clearCacheByTag(tag: string)` for delete all the tagged request. Eg.:\n\n```ts\nthis.http.get('https://my-json-server.typicode.com/typicode/demo/db?id=1', {\n  headers: {\n    [NgHttpCachingHeaders.TAG]: 'foo',\n  }\n}).subscribe(e =\u003e console.log);\n```\n\n## HttpContext\n\nYou can override `NgHttpCachingConfig` methods:\n```ts\n{\n  isExpired?: (entry: NgHttpCachingEntry) =\u003e boolean | undefined | void;\n  isValid?: (entry: NgHttpCachingEntry) =\u003e boolean | undefined | void;\n  isCacheable?: (req: HttpRequest\u003cany\u003e) =\u003e boolean | undefined | void;\n  getKey?: (req: HttpRequest\u003cany\u003e) =\u003e string | undefined | void;\n}\n```\nwith `HttpContextToken`, eg.:\n```ts\nimport { withNgHttpCachingContext } from 'ng-http-caching';\n\nconst context = withNgHttpCachingContext({\n  isExpired: (entry: NgHttpCachingEntry) =\u003e {\n    console.log('context:isExpired', entry);\n  },\n  isCacheable: (req: HttpRequest\u003cany\u003e) =\u003e {\n    console.log('context:isCacheable', req);\n  },\n  getKey: (req: HttpRequest\u003cany\u003e) =\u003e {\n    console.log('context:getKey', req);\n  },\n  isValid: (entry: NgHttpCachingEntry) =\u003e {\n    console.log('context:isValid', entry);\n  }\n});\nthis.http.get('https://my-json-server.typicode.com/typicode/demo/db?id=1', { context }).subscribe(e =\u003e console.log);\n```\n\n## Cache service\n\nYou can inject into your component the `NgHttpCachingService` that expose some utils methods:\n\n```ts\nexport class NgHttpCachingService {\n\n  /**\n   * Return the config\n   */\n  getConfig(): Readonly\u003cNgHttpCachingConfig\u003e;\n\n  /**\n   * Return the queue map\n   */\n  getQueue(): Readonly\u003cMap\u003cstring, Observable\u003cHttpEvent\u003cany\u003e\u003e\u003e\u003e;\n\n  /**\n   * Return the cache store\n   */\n  getStore(): Readonly\u003cNgHttpCachingStorageInterface\u003e;\n\n  /**\n   * Return response from cache\n   */\n  getFromCache\u003cK, T\u003e(req: HttpRequest\u003cK\u003e): Readonly\u003cHttpResponse\u003cT\u003e\u003e | undefined;\n\n  /**\n   * Add response to cache\n   */\n  addToCache\u003cK, T\u003e(req: HttpRequest\u003cK\u003e, res: HttpResponse\u003cT\u003e): boolean;\n\n  /**\n   * Delete response from cache\n   */\n  deleteFromCache\u003cK\u003e(req: HttpRequest\u003cK\u003e): boolean;\n\n  /**\n   * Clear the cache\n   */\n  clearCache(): void;\n\n  /**\n   * Clear the cache by key\n   */\n  clearCacheByKey(key: string): boolean;\n\n  /**\n   * Clear the cache by keys\n   */\n  clearCacheByKeys(keys: Array\u003cstring\u003e): number;\n\n  /**\n   * Clear the cache by regex\n   */\n  clearCacheByRegex\u003cK, T\u003e(regex: RegExp): number;\n\n  /**\n   * Clear the cache by TAG\n   */\n  clearCacheByTag\u003cK, T\u003e(tag: string): number;\n\n  /**\n   * Run garbage collector (delete expired cache entry)\n   */\n  runGc\u003cK, T\u003e(): boolean;\n\n  /**\n   * Return true if cache entry is expired\n   */\n  isExpired\u003cK, T\u003e(entry: NgHttpCachingEntry\u003cK, T\u003e): boolean;\n\n  /**\n   * Return true if cache entry is valid for store in the cache\n   * Default behaviour is whether the status code falls in the 2xx range and response headers cache-control and expires allow cache.\n   */\n  isValid\u003cK, T\u003e(entry: NgHttpCachingEntry\u003cK, T\u003e): boolean;\n\n  /**\n   * Return true if the request is cacheable\n   */\n  isCacheable\u003cK\u003e(req: HttpRequest\u003cK\u003e): boolean;\n\n  /**\n   * Return the cache key.\n   * Default key is http method plus url with query parameters, eg.:\n   * `GET@https://github.com/nigrosimone/ng-http-caching`\n   */\n  getKey\u003cK\u003e(req: HttpRequest\u003cK\u003e): string;\n\n  /**\n   * Return observable from cache\n   */\n  getFromQueue\u003cK, T\u003e(req: HttpRequest\u003cK\u003e): Observable\u003cHttpEvent\u003cT\u003e\u003e | undefined;\n\n  /**\n   * Add observable to cache\n   */\n  addToQueue\u003cK, T\u003e(req: HttpRequest\u003cK\u003e, obs: Observable\u003cHttpEvent\u003cT\u003e\u003e): void;\n\n  /**\n   * Delete observable from cache\n   */\n  deleteFromQueue\u003cK\u003e(req: HttpRequest\u003cK\u003e): boolean;\n}\n```\n\n## Examples\n\nBelow there are some examples of use case.\n\n### Example: exclude specific request from cache\n\nYou can disallow specific request by add the header `X-NG-HTTP-CACHING-DISALLOW-CACHE`, eg.:\n\n```ts\nimport { Component, OnInit } from '@angular/core';\nimport { HttpClient } from \"@angular/common/http\";\nimport { NgHttpCachingHeaders } from 'ng-http-caching';\n\n@Component({\n  selector: 'app-root',\n  templateUrl: './app.component.html',\n  styleUrls: ['./app.component.scss']\n})\nexport class AppComponent implements OnInit {\n\n  constructor(private http: HttpClient) {}\n\n  ngOnInit(): void {\n    // This request will never cache.\n    // Note: all the \"special\" headers in NgHttpCachingHeaders are removed before send the request to the backend.\n    this.http.get('https://my-json-server.typicode.com/typicode/demo/db', {\n      headers: {\n         [NgHttpCachingHeaders.DISALLOW_CACHE]: '1',\n      }\n    }).subscribe(e =\u003e console.log);\n  }\n}\n```\n\n### Example: set specific lifetime for request\n\nYou can set specific lifetime for request by add the header `X-NG-HTTP-CACHING-LIFETIME` with a string value as the number of millisecond, eg.:\n\n```ts\nimport { Component, OnInit } from '@angular/core';\nimport { HttpClient } from \"@angular/common/http\";\nimport { NgHttpCachingHeaders } from 'ng-http-caching';\n\n@Component({\n  selector: 'app-root',\n  templateUrl: './app.component.html',\n  styleUrls: ['./app.component.scss']\n})\nexport class AppComponent implements OnInit {\n\n  constructor(private http: HttpClient) {}\n\n  ngOnInit(): void {\n    // This request will expire from 365 days.\n    // Note: all the \"special\" headers in NgHttpCachingHeaders are removed before send the request to the backend.\n    this.http.get('https://my-json-server.typicode.com/typicode/demo/db', {\n      headers: {\n         [NgHttpCachingHeaders.LIFETIME]: (1000 * 60 * 60 * 24 * 365).toString(),\n      }\n    }).subscribe(e =\u003e console.log);\n  }\n}\n```\n\n### Example: mark specific request as cacheable (if cache strategy is DISALLOW_ALL)\n\nIf you have choose the `DISALLOW_ALL` cache strategy, you can mark specific request as cacheable by adding the header `X-NG-HTTP-CACHING-ALLOW-CACHE`, eg.:\n\n```ts\nimport { Component, OnInit } from '@angular/core';\nimport { HttpClient } from \"@angular/common/http\";\nimport { NgHttpCachingHeaders } from 'ng-http-caching';\n\n@Component({\n  selector: 'app-root',\n  templateUrl: './app.component.html',\n  styleUrls: ['./app.component.scss']\n})\nexport class AppComponent implements OnInit {\n\n  constructor(private http: HttpClient) {}\n\n  ngOnInit(): void {\n    // This request is marked as cacheable (this is necessary only if cache strategy is DISALLOW_ALL)\n    // Note: all the \"special\" headers in NgHttpCachingHeaders are removed before send the request to the backend.\n    this.http.get('https://my-json-server.typicode.com/typicode/demo/db', {\n      headers: {\n         [NgHttpCachingHeaders.ALLOW_CACHE]: '1',\n      }\n    }).subscribe(e =\u003e console.log);\n  }\n}\n```\n\n### Example: clear/flush all the cache\n\nIf user switch the account (logout/login) or the application language, maybe ca be necessary clear all the cache, eg.:\n\n```ts\nimport { Component } from '@angular/core';\nimport { NgHttpCachingService } from 'ng-http-caching';\n\n@Component({\n  selector: 'app-root',\n  templateUrl: './app.component.html',\n  styleUrls: ['./app.component.scss']\n})\nexport class AppComponent {\n\n  constructor(private ngHttpCachingService: NgHttpCachingService) {}\n\n  clearCache(): void {\n    // Clear all the cache\n    this.ngHttpCachingService.clearCache();\n  }\n}\n```\n\n### Example: clear/flush specific cache entry\n\nIf you want delete some cache entry, eg.:\n\n```ts\nimport { Component } from '@angular/core';\nimport { NgHttpCachingService } from 'ng-http-caching';\n\n@Component({\n  selector: 'app-root',\n  templateUrl: './app.component.html',\n  styleUrls: ['./app.component.scss']\n})\nexport class AppComponent {\n\n  constructor(private ngHttpCachingService: NgHttpCachingService) {}\n\n  clearCache(key: string): boolean {\n    // Clear the cache for the provided key\n    return this.ngHttpCachingService.clearCacheByKey(key);\n  }\n}\n```\n\n### Example: clear/flush specific cache entry by RegEx\n\nIf you want delete some cache entry by RegEx, eg.:\n\n```ts\nimport { Component } from '@angular/core';\nimport { NgHttpCachingService } from 'ng-http-caching';\n\n@Component({\n  selector: 'app-root',\n  templateUrl: './app.component.html',\n  styleUrls: ['./app.component.scss']\n})\nexport class AppComponent {\n\n  constructor(private ngHttpCachingService: NgHttpCachingService) {}\n\n  clearCacheByRegex(regEx: RegExp): void {\n    // Clear the cache for the key that match regex\n    this.ngHttpCachingService.clearCacheByRegex(regEx);\n  }\n}\n```\n\n### Example: TAG request and clear/flush specific cache entry by TAG\n\nYou can tag multiple request by adding special header `X-NG-HTTP-CACHING-TAG` with the same tag and \nusing `NgHttpCachingService.clearCacheByTag(tag: \n)` for delete all the tagged request. Eg.:\n\n```ts\nimport { Component, OnInit } from '@angular/core';\nimport { HttpClient } from \"@angular/common/http\";\nimport { NgHttpCachingService } from 'ng-http-caching';\n\n@Component({\n  selector: 'app-root',\n  templateUrl: './app.component.html',\n  styleUrls: ['./app.component.scss']\n})\nexport class AppComponent {\n\n  constructor(private ngHttpCachingService: NgHttpCachingService) {}\n\n  ngOnInit(): void {\n    // This request is tagged with \"foo\" keyword. You can tag multiple requests with the same tag and \n    // using NgHttpCachingService.clearCacheByTag(\"foo\") for delete all the tagged request.\n    this.http.get('https://my-json-server.typicode.com/typicode/demo/db?id=1', {\n      headers: {\n         [NgHttpCachingHeaders.TAG]: 'foo',\n      }\n    }).subscribe(e =\u003e console.log);\n\n    // This request is also tagged with \"foo\" keyword, and has another tag \"baz\".\n    // You can add multiple tags comma separated.\n    this.http.get('https://my-json-server.typicode.com/typicode/demo/db?id=2', {\n      headers: {\n         [NgHttpCachingHeaders.TAG]: 'foo,baz',\n      }\n    }).subscribe(e =\u003e console.log);\n  }\n\n  clearCacheForFoo(): void {\n    // Clear the cache for all the entry have the tag 'foo'\n    this.ngHttpCachingService.clearCacheByTag('foo');\n  }\n}\n```\n\n## Alternatives\n\nAren't you satisfied? there are some valid alternatives:\n\n - [@ngneat/cashew](https://www.npmjs.com/package/@ngneat/cashew)\n - [p3x-angular-http-cache-interceptor](https://www.npmjs.com/package/p3x-angular-http-cache-interceptor)\n - [@d4h/angular-http-cache](https://www.npmjs.com/package/@d4h/angular-http-cache)\n\n\n## Support\n\nThis is an open-source project. Star this [repository](https://github.com/nigrosimone/ng-http-caching), if you like it, or even [donate](https://www.paypal.com/paypalme/snwp). Thank you so much!\n\n## My other libraries\n\nI have published some other Angular libraries, take a look:\n\n - [NgSimpleState: Simple state management in Angular with only Services and RxJS](https://www.npmjs.com/package/ng-simple-state)\n - [NgGenericPipe: Generic pipe for Angular application for use a component method into component template.](https://www.npmjs.com/package/ng-generic-pipe)\n - [NgLet: Structural directive for sharing data as local variable into html component template](https://www.npmjs.com/package/ng-let)\n - [NgForTrackByProperty: Angular global trackBy property directive with strict type checking](https://www.npmjs.com/package/ng-for-track-by-property)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnigrosimone%2Fng-http-caching","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnigrosimone%2Fng-http-caching","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnigrosimone%2Fng-http-caching/lists"}