【问题标题】:How to use CachedResourceLoader as an equivalent mechanism to $templateCache in Angular2?如何使用 CachedResourceLoader 作为 Angular2 中 $templateCache 的等效机制?
【发布时间】:2018-03-07 15:43:21
【问题描述】:

我知道有2similar 对此有疑问,但没有任何解决方案。

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

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

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

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

添加

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'
});

【问题讨论】:

  • 这个问题没有具体说明你打算如何使用它。
  • 我希望 Angular 2 具有与 Angular 1 提供的 templateCache 相同的功能。即第一次使用模板时,它会加载到模板缓存中以便快速检索。您可以将模板直接加载到脚本标签中的缓存中,或者直接使用 $templateCache 服务。

标签: javascript angularjs angular-templatecache


【解决方案1】:

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

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

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

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

{provide: ResourceLoader, useClass: CachedResourceLoader}

已在现有的RESOURCE_CACHE_PROVIDER 导出中定义。

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

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

这里是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)

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

【讨论】:

    猜你喜欢
    • 2016-08-26
    • 2016-03-28
    • 1970-01-01
    • 2016-03-15
    • 1970-01-01
    • 1970-01-01
    • 2017-09-10
    • 2013-10-18
    • 1970-01-01
    相关资源
    最近更新 更多