2017-01-31 19 views
1

我正在關注一個關於Angular2 beta versiopn的課程,其中我有兩個組件,其數據正在嘗試顯示。這是我的app.component:Angular2 - 不顯示來自組件的數據

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(); 
    } 
} 

從作者組分插值數據顯示但不是來自課程部分。 我不知道爲什麼,我該如何調試它?

更新

我設法證明這段代碼的數據:

@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(); 
    } 
} 

如果有人能解釋我是什麼在此代碼的差異,在這個問題的第一個,我會非常感謝,因爲除了組件裝飾器和類聲明之間的空行之外,我看不到任何區別?即使我只是從這裏複製粘貼代碼並創建這個空間,我仍然無法顯示數據,但是當我使用我現在在這裏展示的代碼時,它就可以工作!如何,爲什麼?當我陷入這種情況時,我該如何調試應用程序?而且,當數據沒有顯示時,控制檯中沒有錯誤。

+1

不是一個答案,但我可能會重新考慮,如果你剛開始學習Angular,你會升級到最終版本。我的意思是說,Angular 4 beta已經不在了;)如果你正在尋找教程,我認爲TOH教程涵蓋了一切都很好https://angular.io/docs/ts/latest/tutorial/但是如果你想堅持到測試版,這也沒關係:) – Alex

+0

你在開發者控制檯中得到模板解析錯誤嗎? – Deep

回答

0

我想看看這篇文章:

Difference between Constructor and ngOnInit

它通常是更好的做法,在構造函數初始化您的服務和使用的角度「ngOnInit」打電話給你的服務。文章解釋了爲什麼。