我正在努力学习Angular 2,所以我正在制作一些你好世界的例子.
这是我的代码:
boot.ts
import {bootstrap} from 'angular2/platform/browser'
import {AppComponent} from './app.component'
import {DataService} from './app.dataservice'
bootstrap(AppComponent, [DataService]);
的index.html
...
<body>
<hello-world>Loading...</hello-world>
<hello-world>Loading...</hello-world>
</body>
...
app.component.ts
import {Component} from 'angular2/core';
import {DataService} from './app.dataservice'
@Component({
selector: 'hello-world',
template: '<h1>Hello {{ item }}</h1>'
})
export class AppComponent {
items: Array<number>;
item: number;
constructor(dataService: DataService) {
this.items = dataService.getItems();
this.item = this.items[0];
}
}
app.dataservice.ts
export class DataService {
items: Array<number>;
constructor() {
this.items = [1,2,3];
}
getItems() {
return this.items;
}
}
代码似乎工作正常,因为第一个hello-world自定义标记正在使用ts中的代码正确显示.但是,第二个hello-world标记未被转换.仅显示一个自定义元素.
编辑
我在app.components.ts中添加了新的导入
import {ByeWorld} from './app.byeworld';
并在app.byeworld.ts
import {Component} from 'angular2/core';
@Component({
selector: 'bye-world',
template: '<h1>Bye World</h1>'
})
export class ByeWorld {
constructor() {
}
}
解决方法:
正如标准HTML页面应该有一个< body>内容的标记和一个< head>对于’元数据’的标记,Angular2应用程序应该有一个根标记.要使应用程序工作,你必须初始化它(告诉Angular它是一个应用程序),你通过调用bootstrap()函数来做到这一点.
如果您的根标记(例如< app>)位于正文中,您可以将选择器从自定义标记应用更改为标准标记正文.如果以root身份添加不同的组件,如下所示:
import {bootstrap} from 'angular2/platform/browser'
import {Component} from 'angular2/core';
import {AppComponent} from './app.component'
import {DataService} from './app.dataservice'
@Component({
selector: 'body',
directives: [AppComponent],
template: `
<hello-world>Loading...</hello-world>
<hello-world>Loading...</hello-world>
`
})
class RootComponent {}
bootstrap(RootComponent, [DataService]);
…其余的代码应该可行.
当然,如果在你的HTML中你需要有其他东西(非应用程序内容或其他角度应用程序),你就不会选择body作为Angular2应用程序的根选择器.
希望这有助于您更好地理解事物……
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。