NgUpgrade:升级Angular1组件时无法使用templateUrl

7ivaypg9  于 2022-10-31  发布在  Angular
关注(0)|答案(9)|浏览(185)

我想升级ng 1组件,以便在ng 2组件中使用。
如果我只使用一个模板字符串ng 1组件来升级,它可以工作。但是,如果我改用templateUrl,应用程序会崩溃,并给予我这个错误:

angular.js:13920 Error: loading directive templates asynchronously is not supported
at RemoteUrlComponent.UpgradeComponent.compileTemplate (upgrade-static.umd.js:720)
at RemoteUrlComponent.UpgradeComponent (upgrade-static.umd.js:521)
at new RemoteUrlComponent (remote-url.component.ts:11)
at new Wrapper_RemoteUrlComponent (wrapper.ngfactory.js:7)
at View_AppComponent1.createInternal (component.ngfactory.js:73)
at View_AppComponent1.AppView.create (core.umd.js:12262)
at TemplateRef_.createEmbeddedView (core.umd.js:9320)
at ViewContainerRef_.createEmbeddedView (core.umd.js:9552)
at eval (common.umd.js:1670)
at DefaultIterableDiffer.forEachOperation (core.umd.js:4653)

这里有一个plunk演示我的问题:
https://plnkr.co/edit/2fXvfc?p=info
我已经按照Angular 1 -〉2升级指南,似乎这段代码应该工作。我不太清楚为什么它不工作。

nhaq1z21

nhaq1z211#

我为这个问题找到了一个相当便宜的解决方案。
只要使用template: require('./remote-url.component.html')而不是templateUrl: './remote-url.component.html',它应该工作得很好!

yb3bgrhw

yb3bgrhw2#

在用requireJS和文本插件尝试require后,我发现它不起作用,我设法用'ng-include'使它起作用,如下所示:

angular.module('appName').component('nameComponent', {
template: `<ng-include src="'path_to_file/file-name.html'"></ng-include>`,

我希望这对你有帮助!

zbwhf8kr

zbwhf8kr3#

这真的很让人沮丧,因为Angular的升级文档特别提到可以使用templateUrl。但从来没有提到这个异步问题。我已经找到了一个方法,通过使用$templateCache来解决这个问题。我不想更改我的angular 1指令,因为它是我的angular 1应用程序使用的,也将被angular 4应用程序使用。所以我不得不找到一种方法来动态修改它。我使用了$delegate,$provider和$templateCache。我的代码如下所示。我还使用它来删除replace属性,因为它已被弃用。

function upgradeDirective(moduleName, invokedName) {
    /**get the invoked directive */
    angular.module(moduleName).config(config);

    config.$inject = ['$provide'];
    decorator.$inject = ['$delegate', '$templateCache'];

    function config($provide) {
        $provide.decorator(invokedName + 'Directive', decorator);
    }

    function decorator($delegate, $templateCache) {
        /**get the directive reference */
        var directive = $delegate[0];

        /**remove deprecated attributes */
        if (directive.hasOwnProperty('replace')){
            delete directive.replace;
        }

        /**check for templateUrl and get template from cache */
        if (directive.hasOwnProperty('templateUrl')){
            /**get the template key */
            var key = directive.templateUrl.substring(directive.templateUrl.indexOf('app/'));

            /**remove templateUrl */
            delete directive.templateUrl;

            /**add template and get from cache */
            directive.template = $templateCache.get(key);
        }

        /**return the delegate */
        return $delegate;
    }
}

upgradeDirective('moduleName', 'moduleDirectiveName');
zqry0prt

zqry0prt4#

这里给出的大多数答案都涉及到以某种方式预加载模板,以便使其可与指令同步使用。
如果您不想这样做-例如,如果您有一个包含许多模板的大型AngularJS应用程序,并且您不想预先下载所有模板-您可以简单地将指令 Package 在一个同步加载的版本中。
例如,如果您有一个名为myDirective的指令,其中有一个异步加载的templateUrl,而您不想预先下载它,则可以这样做:

angular
  .module('my-module')
  .directive('myDirectiveWrapper', function() {
    return {
      restrict: 'E',
      template: "<my-directive></my-directive>",
    }
  });

那么你的Upgraded Angular指令只需要在它对扩展的UpgradeComponentsuper()调用中提供'myDirectiveWrapper'而不是'myDirective'

t98cgbkg

t98cgbkg5#

解决这个问题的一个技术含量很低的解决方案是将模板加载到index.html中,并为它们分配与指令所查找的templateUrls相匹配的ID,即:

<script type="text/ng-template" id="some/file/path.html">
  <div>
    <p>Here's my template!</p>
  </div>
</script>

然后Angular会自动将模板放入$templateCache中,这是UpgradeComponent的compileTemplate开始查找模板的地方,因此无需更改指令中的templateUrl,一切都会正常工作,因为id与templateUrl匹配。
如果您检查UpgradeComponent的源代码(见下文),您可以看到处理获取url的代码被注解掉了,所以它一定在工作中,但目前这可能是一个可行的解决方案,甚至是一个可脚本化的解决方案。

private compileTemplate(directive: angular.IDirective): angular.ILinkFn {
    if (this.directive.template !== undefined) {
      return this.compileHtml(getOrCall(this.directive.template));
    } else if (this.directive.templateUrl) {
      const url = getOrCall(this.directive.templateUrl);
      const html = this.$templateCache.get(url) as string;
      if (html !== undefined) {
        return this.compileHtml(html);
      } else {
        throw new Error('loading directive templates asynchronously is not supported');
        // return new Promise((resolve, reject) => {
        //   this.$httpBackend('GET', url, null, (status: number, response: string) => {
        //     if (status == 200) {
        //       resolve(this.compileHtml(this.$templateCache.put(url, response)));
        //     } else {
        //       reject(`GET component template from '${url}' returned '${status}: ${response}'`);
        //     }
        //   });
        // });
      }
    } else {
      throw new Error(`Directive '${this.name}' is not a component, it is missing template.`);
    }
  }
moiiocjp

moiiocjp6#

如果您不想修改Webpack配置,快速/不彻底的解决方案是使用raw-loader导入语法:
template: require('!raw-loader!./your-template.html')

cmssoen2

cmssoen27#

作为一个变通方案,我使用$templateCache和$templateRequest将模板放在$templateCache中,以获取Angular所需的模板,在AngularJS上运行如下:

app.run(['$templateCache', '$templateRequest', function($templateCache, $templateRequest) {
        var templateUrlList = [
            'app/modules/common/header.html',
            ...
        ];
        templateUrlList.forEach(function (templateUrl) {
            if ($templateCache.get(templateUrl) === undefined) {
                $templateRequest(templateUrl)
                    .then(function (templateContent) {
                        $templateCache.put(templateUrl, templateContent);
                    });
            }
        });
    }]);
sbtkgmzw

sbtkgmzw8#

我已经创建了一个方法实用程序来解决这个问题,基本上它使用requireJS和“text.js”将模板url内容添加到angular的templateCache中:

initTemplateUrls(templateUrlList) {
    app.run(function ($templateCache) {
      templateUrlList.forEach(templateUrl => {
        if ($templateCache.get(templateUrl) === undefined) {
          $templateCache.put(templateUrl, 'temporaryValue');
          require(['text!' + templateUrl],
            function (templateContent) {
              $templateCache.put(templateUrl, templateContent);
            }
          );
        }
      });
    });

例如,您应该将此方法实用程序放在appmodule.ts中,然后创建一个将要从Angular 指令升级的templateUrls列表,例如:

const templateUrlList = [
      '/app/@fingerprint@/common/directives/grid/pGrid.html',
    ];
ikfrs5lh

ikfrs5lh9#

我使用webpack required.context来实现这一点:

模板-工厂.js

import {resolve} from 'path';

/**
 * Wrap given context in AngularJS $templateCache
 * @param ctx - A context module
 * @param dir - module directory
 * @returns {function(...*): void} - AngularJS Run function
 */
export const templatesFactory = (ctx, dir, filename) => {
    return $templateCache => ctx.keys().forEach(key => {

        const templateId = (() => {
            switch (typeof filename) {
                case 'function':
                    return resolve(dir, filename(key));
                case 'string':
                    return resolve(dir, filename);
                default:
                    return resolve(dir, key);
            }
        })();

        $templateCache.put(templateId, ctx(key));
    });
};

应用程序. html-捆绑包.js

import {templatesFactory} from './templates-factory';

    const ctx = require.context('./', true, /\.html$/);

    export const AppHtmlBundle = angular.module('AppHtmlBundle', [])
        .run(templatesFactory(ctx, __dirname))
        .name;

不要忘记将html-loader添加到您webpack.config.js中:

[{
    test: /\.html$/,
    use: {
        loader: 'html-loader',
        options: {
            minimize: false,
            root: path.resolve(__dirname, './src')
        }
    }
}]

你也可能需要将相对路径转换为绝对路径。我使用我自己编写的Babel插件ng-template-url-absolutify来实现这个目的:

[{
    test: /\.(es6|js)$/,
    include: [path.resolve(__dirname, 'src')],
    exclude: /node_modules/,
    loader: 'babel-loader',
    options: {
        plugins: [
            '@babel/plugin-syntax-dynamic-import',
            ['ng-template-url-absolutify', {baseDir: path.resolve(__dirname, 'src'), baseUrl: ''}]
        ],

        presets: [['@babel/preset-env', {'modules': false}]]
    }
},

相关问题