我试图在Angular2中使用templateUrl访问自定义构建的html。
这是我的login.component.ts
import {Component} from '@angular/core';
@Component({
selector: 'login' ,
templateUrl : './login.component.html'
})
export class loginComponent{
}
这是我的login.component.html
<div class="container">
<input type="text" placeholder="username">
<input type="text" placeholder="password">
<button>Login</button>
</div>
我的目录结构在同一位置都有login.component.ts和login.component.html。
当我编译这段代码时,我收到一个错误说明
localhost:8081 / login.component.html找不到404
未处理的承诺拒绝:无法加载login.component.html;区域:;任务:Promise.then;值:无法加载login.component.html undefined
您需要将您的应用配置为使用相对网址
tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
//... other options
}
}
login.component.ts
从'@ angular / core'导入{Component};
@Component({
moduleId: module.id, // fully resolved filename; defined at module load time
selector: 'login' ,
templateUrl : './login.component.html'
})
export class loginComponent{
}
关键的一课是在@Component装饰器中设置moduleId:module.id!如果没有moduleId设置,Angular将在相对于应用程序根目录的路径中查找我们的文件。
并且不要忘记tsconfig.json中的“module”:“commonjs”。
这个组件相对路径解决方案的优点在于我们可以(1)轻松地重新打包我们的组件,以及(2)轻松地重用组件......所有这些都不需要更改@Component元数据。
https://blog.thoughtram.io/angular/2016/06/08/component-relative-paths-in-angular-2.html
如果你使用webpack并面临这个问题。
我通过替换解决了这个问题
loaders: ['awesome-typescript-loader', 'angular2-template-loader?keepUrl=true']
至
loaders: ['awesome-typescript-loader', 'angular2-template-loader']
(代表OP发布)。
通过使用解决了这个问题
require('./login.component.html')
在我的模板下。
通常这种类型的错误是由于Angular无法找到指定的路径。我通过更改@Component中templateUrl中的html文件路径解决了这个问题。