2016-03-03 48 views
1

我似乎無法獲得這個數據。這個英雄顯示在列表中。我把一個警報(this.heroes [0] .name);它顯示的數據如此this._service.getHeroes();是返回數據Angular 2 * ngFor不顯示數據

app.html

<div style="width:1000px;margin:auto"> 
    <ul> 
     <li *ngFor="#hero of heroes"> 
      <span>{{hero.name}}</span> 
     </li> 
    </ul> 
</div> 

app.component.ts

import {Component} from 'angular2/core'; 
import {RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router'; 
import {HeroService} from './heroes/hero.service'; 
import {Hero} from './heroes/hero'; 

@Component({ 
    selector: 'my-app', 
    templateUrl: 'templates/app.html', 
    providers: [HeroService], 
    directives: [ROUTER_DIRECTIVES] 
}) 

export class AppComponent { 
    heroes: Hero[]; 

    constructor(private _service: HeroService) { } 

    ngOnInit() { 
     this.heroes = this._service.getHeroes(); 
    } 
} 
+0

你把alert()放在哪裏?你可以做一個plnkr或jsfiddle嗎? – martin

+0

這是否與舊的ng-repeat =「英雄英雄」一起工作。閱讀本文以供參考:https://coryrylan.com/blog/angular-2-ng-for-syntax –

回答

1

試試這個第一,看看它的工作原理:

<li ng-repeat="hero in heroes"> 
    {{hero.name}} 
</li> 

如果t他的作品可能有一個不支持* ngFor語法的舊角度版本(我認爲這在新版本的角度2中是受支持的)。

+0

謝謝Lisa我會嘗試一下。它也發生在我身上,我可能需要一個數字財產for * ngFor才能工作。我的Heores類只有名稱的字符串屬性。 – Mark

+0

我的package.json和index.html沒有針對Angular 2和依賴關係進行正確配置。現在它工作正常。謝謝麗莎 – Mark

+0

啊!我懂了。當我切換到角度2時,我會記住這一點。 –

0

我已經做了更多的研究,沒有顯示數據。例如:

<h2>My favorite hero is {{ myHero }}</h2> 

得到而

<h2>My favorite hero is </h2> 

顯示

一個空行(其中myHero是一個人口稠密的字符串)

我最喜歡的英雄是

我要去改變Angular 2的Beta版本,看看它是否有幫助