Carlos Cifuentes
AngularJS → Angular reference

$http cache / $cacheFactory in modern Angular

HttpClient has no cache option. Caching is explicit code in the service that owns the data, usually a stored observable with shareReplay.

Before · AngularJS
app.factory('CountryService', function ($http, $cacheFactory) {
  var cache = $cacheFactory('countries');
  return {
    getAll: function () {
      return $http.get('/api/countries', { cache: cache });
    },
    clear: function () { cache.removeAll(); }
  };
});
After · Angular
@Injectable({ providedIn: 'root' })
export class CountryService {
  private http = inject(HttpClient);
  private countries$?: Observable<Country[]>;

  getAll() {
    this.countries$ ??= this.http
      .get<Country[]>('/api/countries')
      .pipe(shareReplay({ bufferSize: 1, refCount: false }));
    return this.countries$;
  }

  clear() {
    this.countries$ = undefined;
  }
}

What changes

  • shareReplay keeps the last response and shares one request between all subscribers, including the ones that arrive while it is in flight.
  • For data keyed by id or URL, keep a Map of observables in the service, or write an interceptor that stores GET responses.
  • Invalidation is your code: clear the stored entry after a write that changes the data.

Migration tip. List every endpoint that used cache: true and ask whether it still needs it. Reference data such as countries usually does; in other places the cache was hiding duplicate requests that the new component structure no longer makes.

Related

Planning a migration or a micro-frontend platform?

In a 20-minute call you describe your situation and I tell you how I'd approach it. If it isn't worth doing yet, I'll say so.

Message me on LinkedIn