How to use CachedResourceLoader as an equivalent mechanism to $templateCache in Angular2?

749 Views Asked by At

I know there are 2 similar questions about this but with no solution for any of them.

So I found this issue in Angular repo where they ask for the same, i.e an alternative for templateCache in Angular 2 but they close it saying you can use CachedResourceLoader.

So my question is how to use this CachedResourceLoader to replace the templateCache, I have been searching on google about this but couldn't find any related content so maybe I am not pointing to the right direction or I missed something.

The answer to this question could be a valid answer for the other 2 similar questions.

Code example for the functionality that templateCache provided in AngularJS:

Adding:

var myApp = angular.module('myApp', []);
myApp.run(function($templateCache) {
  $templateCache.put('templateId.html', 'This is the content of the template');
});

Retrieval via $templateCache:

$templateCache.get('templateId.html')

Or retrieval:

myApp.component('myComponent', {
   templateUrl: 'templateId.html'
});
1

There are 1 best solutions below

0
On BEST ANSWER

CachedResourceLoader is existing yet undocumented Angular 2+ substitution for AngularJS $templateCache:

An implementation of ResourceLoader that uses a template cache to avoid doing an actual ResourceLoader.

The template cache needs to be built and loaded into window.$templateCache via a separate mechanism.

It is supposed to work by providing ResourceLoader provider:

{provide: ResourceLoader, useClass: CachedResourceLoader}

Which was already defined in existing RESOURCE_CACHE_PROVIDER export.

And window.$templateCache is supposed to contain pairs of URLs and responses.

Since ResourceLoader should be specified before compilation, it should be provided not in application module but in compiler options.

Here is an example:

import {RESOURCE_CACHE_PROVIDER} from '@angular/platform-browser-dynamic';
import {COMPILER_OPTIONS} from '@angular/core';

window['$templateCache'] = { 'app.html': `...`};

platformBrowserDynamic({
  provide: COMPILER_OPTIONS,
  useValue: { providers: [RESOURCE_CACHE_PROVIDER] },
  multi: true
}).bootstrapModule(AppModule)

As opposed to AngularJS $templateCache, CachedResourceLoader doesn't allow to make requests for missing templates. This is desirable behaviour most of the time. If it has to be changed, a custom implementation that extends default ResourceLoader implementation can be used instead.