我已经使用了包含AppComponent的angular-cli创建了一个项目,如下所示:
- import { Component } from '@angular/core';
- @Component({
- selector: 'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.css']
- })
- export class AppComponent {
- title = 'app works!';
- }
和app.component.html as
- <h1>
- Good Morning,{{title}}
- </h1>
所以当我使用ng构建它生成一些这样的文件./dist/main.bundle.js,其内容一些代码如下 –
- /* 586 */
- /***/ function(module,exports) {
- module.exports = "<h1>\n Good Morning,{{title}}\n</h1>\n"
- /***/ },/* 587 */
这意味着,在编译时,编译器/ bundle-er正在读取html文件,并将它们连接到生成的js文件中。
但在我的情况下,html也是从服务器端动态和内容驱动的。可以说,我的模板文件不是html,而是app.component.jsp,而是驻留在一些不同的服务器或文件夹上。
此外,JSP文件有时返回< h1>早安,{{title}}< / h1>
并且有时< h1> Good Afternoon,{{title}}< / h1>取决于当前的服务器时间。
如何实现这个功能?
我所了解的是,我需要定义一些加载器函数说:loadDynamicTemplate(template_url)
并且需要在Component decorator模板属性上使用该loader功能。在这种情况下,当生成main.bundle.JS时,它也会使用该函数。所以在运行时角度会调用这个函数,并通过ajax加载HTML并使用它。
更新1
Here我发现SystemJS和Webpack有一些区别。我也发现如果我们可以使用SystemJS,我们可以在运行时加载HTML文件。所以我相信这个问题可以通过SystemJS配置来解决。但是,另一个问题是发挥作用,虽然我认为这可能是一个单独的问题。所以我发布了一个新的问题来排除here。
解决方法
你可以在我的模板组件中使用[innerHtml]这样的东西(我没有测试):
- @Component({
- selector: 'my-template',template: `
- <div [innerHtml]="myTemplate">
- </div>
- `})
- export public class MyTemplate {
- private myTemplate: any = "";
- @Input() url: string;
- constructor(http: Http) {
- http.get("/path-to-your-jsp").map((html:any) => this.myTemplate = html);
- }
- }