2016-03-03 117 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版本,看看它是否有帮助