我正在学习Angular2 beta versiopn课程,其中我有2个组件,我试图显示其数据。这是我的app.component:
import {Component} from 'angular2/core';
import {CoursesComponent} from './courses.component'
import {AuthorsComponent} from './authors.component'
@Component({
selector: 'my-app',
template: `
<h1>Hello Angular 2 App</h1>
<courses></courses>
<authors></authors>
`,
directives: [CoursesComponent, AuthorsComponent]
})
export class AppComponent { }
这是课程组成部分:
import {Component} from 'angular2/core';
import {CourseService} from './course.service';
import {AutoGrowDirective} from './auto-grow.directive';
@Component({
selector: 'courses',
template: `
<h2>{{ title }}</h2>
<input type="text" autoGrow />
<ul>
<li *ngFor="#course of courses">
{{ course }}
</li>
</ul>
`,
providers: [CourseService],
directives: [AutoGrowDirective]
})
export class CoursesComponent {
title: string = "The title of courses page";
courses;
constructor(courseService: CourseService) {
this.courses = courseService.getCourses();
}
}
这是作者组成部分:
import {Component} from 'angular2/core'
import {AuthorService} from './author.service'
@Component({
selector: 'authors',
template: `
<h2>{{ title }}</h2>
<ul>
<li *ngFor="#author of authors">
{{ author }}
</li>
</ul>
`,
providers: [AuthorService]
})
export class AuthorsComponent {
title: string = "The title of authors page";
authors;
constructor(authorService: AuthorService) {
this.authors = authorService.getAuthors();
}
}
来自authors组件的插值数据正在显示,但不会显示在课程组件中。 我不知道为什么,我该如何调试呢?
更新
我设法用这段代码显示数据:
@Component({
selector: 'courses',
template: `
<h2>{{ title }}</h2>
<input type="text" autoGrow />
<ul>
<li *ngFor="#course of courses">
{{ course }}
</li>
</ul>
`,
providers: [CourseService],
directives: [AutoGrowDirective]
})
export class CoursesComponent {
title: string = "The title of courses page";
courses;
constructor(courseService: CourseService) {
this.courses = courseService.getCourses();
}
}
如果有人能解释我这个代码和问题中的第一个有什么区别,我会非常感激,因为除了组件装饰器和类之间的空行之外,我看不到任何区别宣言?即使我只是从这里复制粘贴代码并创建该空间我仍然无法显示数据,但是当我使用我现在在这里展示的代码时,它就可以了!怎么样,为什么?在这种情况下,我怎样才能调试应用程序?而且,当数据没有显示时,控制台中没有错误。
答案 0 :(得分:1)
我会查看这篇文章:
Difference between Constructor and ngOnInit
通常最好在构造函数中初始化服务,并使用角度“ngOnInit”来调用您的服务。文章详细解释了原因。