我想升级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升级指南,似乎这段代码应该工作。我不太清楚为什么它不工作。
9条答案
按热度按时间nhaq1z211#
我为这个问题找到了一个相当便宜的解决方案。
只要使用
template: require('./remote-url.component.html')
而不是templateUrl: './remote-url.component.html'
,它应该工作得很好!yb3bgrhw2#
在用requireJS和文本插件尝试require后,我发现它不起作用,我设法用'ng-include'使它起作用,如下所示:
我希望这对你有帮助!
zbwhf8kr3#
这真的很让人沮丧,因为Angular的升级文档特别提到可以使用templateUrl。但从来没有提到这个异步问题。我已经找到了一个方法,通过使用$templateCache来解决这个问题。我不想更改我的angular 1指令,因为它是我的angular 1应用程序使用的,也将被angular 4应用程序使用。所以我不得不找到一种方法来动态修改它。我使用了$delegate,$provider和$templateCache。我的代码如下所示。我还使用它来删除replace属性,因为它已被弃用。
zqry0prt4#
这里给出的大多数答案都涉及到以某种方式预加载模板,以便使其可与指令同步使用。
如果您不想这样做-例如,如果您有一个包含许多模板的大型AngularJS应用程序,并且您不想预先下载所有模板-您可以简单地将指令 Package 在一个同步加载的版本中。
例如,如果您有一个名为
myDirective
的指令,其中有一个异步加载的templateUrl
,而您不想预先下载它,则可以这样做:那么你的Upgraded Angular指令只需要在它对扩展的
UpgradeComponent
的super()
调用中提供'myDirectiveWrapper'
而不是'myDirective'
。t98cgbkg5#
解决这个问题的一个技术含量很低的解决方案是将模板加载到index.html中,并为它们分配与指令所查找的templateUrls相匹配的ID,即:
然后Angular会自动将模板放入$templateCache中,这是UpgradeComponent的compileTemplate开始查找模板的地方,因此无需更改指令中的templateUrl,一切都会正常工作,因为id与templateUrl匹配。
如果您检查UpgradeComponent的源代码(见下文),您可以看到处理获取url的代码被注解掉了,所以它一定在工作中,但目前这可能是一个可行的解决方案,甚至是一个可脚本化的解决方案。
moiiocjp6#
如果您不想修改Webpack配置,快速/不彻底的解决方案是使用raw-loader导入语法:
template: require('!raw-loader!./your-template.html')
cmssoen27#
作为一个变通方案,我使用$templateCache和$templateRequest将模板放在$templateCache中,以获取Angular所需的模板,在AngularJS上运行如下:
sbtkgmzw8#
我已经创建了一个方法实用程序来解决这个问题,基本上它使用requireJS和“text.js”将模板url内容添加到angular的templateCache中:
例如,您应该将此方法实用程序放在appmodule.ts中,然后创建一个将要从Angular 指令升级的templateUrls列表,例如:
ikfrs5lh9#
我使用webpack required.context来实现这一点:
模板-工厂.js
应用程序. html-捆绑包.js
不要忘记将html-loader添加到您webpack.config.js中:
你也可能需要将相对路径转换为绝对路径。我使用我自己编写的Babel插件ng-template-url-absolutify来实现这个目的: