1

我知道有2 个 类似的问题,但没有任何解决方案。

所以我在Angular repo中发现了这个问题,他们要求相同,即Angular 2中templateCache的替代方案,但他们关闭它说你可以使用CachedResourceLoader。

所以我的问题是如何使用这个 CachedResourceLoader 来替换 templateCache,我一直在谷歌上搜索这个但找不到任何相关的内容,所以也许我没有指向正确的方向或者我错过了一些东西。

这个问题的答案可能是其他 2 个类似问题的有效答案。

AngularJS 中 templateCache 提供的功能的代码示例:

添加

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

通过 $templateCache检索:

$templateCache.get('templateId.html')

或检索:

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

1 回答 1

4

CachedResourceLoader现有但未记录的 Angular 2+ 替代 AngularJS $templateCache

ResourceLoader 的实现,它使用模板缓存来避免执行实际的 ResourceLoader。

模板缓存需要通过单独的机制构建并加载到 window.$templateCache 中。

它应该通过提供提供者来工作ResourceLoader

{provide: ResourceLoader, useClass: CachedResourceLoader}

已在现有RESOURCE_CACHE_PROVIDER导出中定义。

并且window.$templateCache应该包含成对的 URL 和响应。

由于ResourceLoader应在编译前指定,因此不应在应用程序模块中提供,而应在编译器选项中提供。

这是一个例子

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)

与 AngularJS不同$templateCacheCachedResourceLoader它不允许对缺少的模板提出请求。大多数时候这是理想的行为。如果必须更改,可以使用扩展默认ResourceLoader实现的自定义实现。

于 2017-09-26T17:22:11.433 回答