Carlos Cifuentes
AngularJS → Angular reference

$templateCache / $cacheFactory in modern Angular

$templateCache is not needed: templates are compiled into the JavaScript bundle at build time. Data caching with $cacheFactory moves into services.

Before · AngularJS
app.run(function ($templateCache) {
  $templateCache.put('user-card.html',
    '<div class="card">{{ vm.user.name }}</div>');
});

app.factory('CountryService', function ($http, $cacheFactory) {
  var cache = $cacheFactory('countries');
  return {
    list: function () { return $http.get('/api/countries', { cache: cache }); }
  };
});
After · Angular
@Component({
  selector: 'app-user-card',
  templateUrl: './user-card.component.html', // compiled at build time
})
export class UserCardComponent { user = input.required<User>(); }

@Injectable({ providedIn: 'root' })
export class CountryService {
  private http = inject(HttpClient);
  private countries$ = this.http.get<Country[]>('/api/countries')
    .pipe(shareReplay(1));

  list() { return this.countries$; }
}

What changes

  • templateUrl files are compiled by the build; the html2js or gulp step that filled $templateCache goes away.
  • $http with a cache option becomes shareReplay on the observable, or an interceptor when many endpoints need the same policy.
  • $cacheFactory used as a key-value store becomes a Map held by a service.

Migration tip. Decide when each cache is invalidated before porting it. Many $cacheFactory caches had no invalidation and served stale data until the page was reloaded.

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