2017-01-25 40 views
11

我正在嘗試遵循Angular 2網站的官方教程。 This tutorialAngular 2未使用的標籤錯誤

我得到的原子IDE下列錯誤:

未使用label.at 8號線第1欄

不能分配給「英雄」,因爲它不是一個variable.at線8山坳7

以下是我的代碼:

import { Component } from '@angular/core'; 
 

 
export class Hero { 
 
    id: number; 
 
    name: string; 
 
} 
 

 
hero: Hero = { 
 
    id: 1, 
 
    name: 'Windstorm' 
 
}; 
 

 
@Component({ 
 
    selector: 'my-app', 
 
    template: `<h1>{{title}}</h1> 
 
     <h2>{{hero.name}} details!</h2>` 
 
}) 
 

 
export class AppComponent { 
 
    title = 'Tour of Heroes'; 
 
    hero = 'Windstorm'; 
 
}

而結果:

Screen Shot

我做了什麼錯?幫助表示讚賞。

+1

由它的外觀英雄是組件中的字符串屬性,但您正試圖在模板中顯示hero.name。 – toskv

回答

20

根據你指的是本教程中,hero場初始化應該是AppComponent內:

import { Component } from '@angular/core'; 
 

 
export class Hero { 
 
    id: number; 
 
    name: string; 
 
} 
 

 
@Component({ 
 
    selector: 'my-app', 
 
    template: `<h1>{{title}}</h1> 
 
     <h2>{{hero.name}} details!</h2>` 
 
}) 
 

 
export class AppComponent { 
 
    title = 'Tour of Heroes'; 
 
    hero: Hero = { 
 
     id: 1, 
 
     name: 'Windstorm' 
 
    }; 
 
}

+2

'hero'已在組件中初始化。問題在於,當模板期望它是一個具有屬性'name'的對象時,'hero'是一個字符串。這就是爲什麼它不起作用,不是因爲'hero'沒有在組件中初始化。 – GillesC

+0

謝謝!這工作! –

+0

@GillesC'hero'對象是在組件的外部創建的,沒有let或var關鍵字(請參閱原始代碼段的第8行)。即使在渲染之前,這也會導致語法錯誤,我想。 – admax

2

只要保持以下的教程,你會找到答案一稍後在頁面上:

export class AppComponent { 
    title = 'Tour of Heroes'; 
    heroes = HEROES; 
    selectedHero: Hero; 
    onSelect(hero: Hero): void { 
    this.selectedHero = hero; 
} 

參考:https://angular.io/tutorial/toh-pt3