【问题标题】:Alternatives to $templateCache in Angular2Angular2 中 $templateCache 的替代品
【发布时间】:2016-03-28 21:34:29
【问题描述】:

当我们想到在 Angular2 或 Angular1.X 中使用 template 时,我们知道下面是一种基本的写法:

template: './template-ninja.html'

在 Angular1.X 中,我们之前可以缓存所有带有 $templateCache.put() 的模板,如下所示:

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

这将减少http请求的数量。 我想知道如何使用 Angular2 实现相同的功能。有人可以帮忙吗? 谢谢。

【问题讨论】:

    标签: angular


    【解决方案1】:

    我还不知道有什么库或工具可以缓存 Angular 2 的模板,但到目前为止,我很高兴只使用内联模板而不是外部文件。使用 es6 反引号字符作为模板,它允许您在 JavaScript 中编写多行 HTML 并将所有内容保存在一个文件中。

    https://github.com/angular-in-action/chapter2/blob/master/client/components/dashboard.ts#L12

    【讨论】:

      【解决方案2】:

      使用以下替代方法:

      • 导入 RuntimeCompiler、反射器、ComponentFactory、ComponentResolver、ReflectorComponentResolver 和 ReflectionInfo
      • 注入运行时编译器
      • 创建一个 ComponentResolver 实例
      • 调用 ComponentResolver.resolveComponent(SomeComponent)
      • 检查 reflector.propMetadata 的缓存结果
      it('应该缓存结果', inject([AsyncTestCompleter], (async) => { PromiseWrapper .all([ComponentResolver.resolveComponent(SomeComponent), ComponentResolver.resolveComponent(SomeComponent)]) .then((protoViewRefs) => { 期望(protoViewRefs[0]).toBe(protoViewRefs[1]); async.done(); }); }));

      注解是另一种方式:

      it('应该从注解中读取模板', 注入([AsyncTestCompleter,编译器],(异步,编译器)=> { ComponentResolver.resolveComponent(SomeComponent) .then((hostViewFactoryRef) => { 期望(hostViewFactoryRef.internalHostViewFactory).toBe(someHostViewFactory); async.done(); }); }));

      参考文献

      【讨论】:

        【解决方案3】:

        gulp-inline-ng2-模板

        目前最好的解决方案是 gulp-inline-ng2-template。

        这需要一个带有 templateUrl 属性的组件,加上一个 html 文件,然后将其转换为带有内联模板的组件。

        https://github.com/ludohenin/gulp-inline-ng2-template

        【讨论】:

          【解决方案4】:

          gulp-ng2-template-wrap

          嗨,

          希望这对您有所帮助:我刚刚编写了一个小模块,允许您将所有 html 文件捆绑到单个 ES6 模块中。

          https://github.com/evgenys91/gulp-ng2-template-wrap

          【讨论】:

            猜你喜欢
            • 2016-08-26
            • 1970-01-01
            • 2017-01-23
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-04-02
            • 2010-11-08
            相关资源
            最近更新 更多