gpt4 book ai didi

angular - 无法在 Angular 2 中找到导入组件的模板 html

转载 作者:太空狗 更新时间:2023-10-29 17:15:30 24 4
gpt4 key购买 nike

我正在开发一个包含多个组件的 Angular2 演示。该演示使用 AppComponent 进行引导,我在 AppComponent 的模板 html 中导入了其他组件。我成功设置了演示并看到了 AppComponent 的内容,但未能加载其他组件。

这是我的 angular2 组件的代码示例

app.component.html

<div id="map">
<navigator></navigator>
</div>

应用程序组件.ts

import {Component, View} from 'angular2/core';
import {NavigatorComponent} from '../components/navigator/navigator.component'

@Component({
selector: 'app'
})
@View({
templateUrl: './app/app.component.html',
directives: [NavigatorComponent]
})
export class AppComponent { }

导航器.component.html

<input type="text">

导航器.component.ts

import {Component, View} from 'angular2/core';

@Component({
selector: 'navigator'
})
@View({
templateUrl: './components/navigator/navigator.component.html'
})
export class NavigatorComponent { }

当我设置服务器并尝试查看应用程序时,出现以下错误

"NetworkError: 404 Not Found - http://localhost:3000/components/navigator/navigator.component"

Error: XHR error (404 Not Found) loading http://localhost:3000/components/navigator/navigator.component
Error loading http://localhost:3000/components/navigator/navigator.component as "../components/navigator/navigator.component" from http://localhost:3000/app/app.component.js

显然,服务器试图找到一个 navigator.component,但它不存在。然而,当我尝试 http://localhost:3000/components/navigator/navigator.component.html , 我成功地看到了带有文本框的页面。

所以问题似乎是缺少 html 扩展,但我不知道它是怎么发生的。

我将不胜感激任何解决问题的建议和答案。提前致谢。


如果您想完整体验该错误,请转到项目的 repo ( https://github.com/haoliangyu/angular2-leaflet-starter ) 并执行以下步骤:

  1. 取消注释 public_src/app/app.component.ts

    中的第 12 行
  2. 设置应用

  3. 进入localhost:3000查看错误


更新:

这个问题是通过抵制 SystemJS 配置中的其他组件解决的,比如

System.config({
defaultJSExtension: true,
packages: {
'app': {
format: 'register'
},
'components/navigator': {
format: 'register'
}
}
});

这有助于应用找到其他组件:)

最佳答案

问题不在于找不到模板文件。但是它无法加载 navigator.component.js

它正在尝试从 http://localhost:3000/components/navigator/navigator.component 加载它,但它应该从 map “app”加载,因此:http://localhost:3000/app/components/navigator/navigator.component.js . js 扩展将由 SystemJS 配置中的默认扩展集添加。

app.component.ts 中注释第 12 行后错误消失的原因是即使 navigator.component.ts 的导入语句仍然保留在代码中, typescript 编译器不会将其添加到实际输出中,因为该类未在当前文件中使用。

我无法安装您的项目,因为您似乎已经对其进行了一些更改。但我相信解决这个问题的方法是更改​​ app.component.tsnavigator.component 的导入位置:

import {NavigatorComponent} from './../components/navigator/navigator.component'

请注意我是如何在当前文件夹 ./ 前面添加


更好的做法是在您的 index.html 中添加一个基本的 href 标签:

<base href="http://localhost/app/">

或者以 http://localhost 实际上指的是应用程序文件夹而不是其父文件夹的方式从 app 文件夹为您的网站提供服务

关于angular - 无法在 Angular 2 中找到导入组件的模板 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34467914/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com