【发布时间】:2016-06-03 06:44:58
【问题描述】:
我遇到了一个对我来说似乎有点神秘的错误。也许一些新的眼睛可以发现我的错误!
我有一个详细组件和一个列表组件,我从服务器检索数据。我的列表组件就像一个魅力,但我在使用细节组件时遇到了麻烦。来自服务器的数据是正确的,但是当我尝试将其打印到浏览器时,它给了我未定义的错误(无法获取未定义的名称)。在 ngOnInit 方法中一切正常,它按预期将我的数据记录到控制台。以下是详细组件中我的代码的相关部分:
export class HeroDetailComponent implements OnInit {
@Input() hero: Hero; //also tried without the input in front of hero
constructor(public _routeParams: RouteParams, public _service: Service) {
}
ngOnInit() {
let id = this._routeParams.get('id');
this._service.getById(id)
.subscribe(hero => {
this.hero = hero;
console.log("hero: ", this.hero); //the correct data is logged!
});
}
}
在模板中:
<h1>Hero: {{hero.name}}</h1>
作为参考,列表组件中的相同相关代码列出了所有英雄并且完美运行。
export class HeroListComponent implements OnInit {
name: string;
id: string;
date: string;
heroes: Array<Hero>;
constructor(public _service: Service, public _router: Router) {
}
ngOnInit() {
this.getHeroes();
}
getHeroes() {
this._service.getHeroes()
.subscribe(heroes => this.heroes = heroes);
}
}
模板:
<table>
<tr *ngFor="let hero of heroes" >
<td>{{hero.name}}</td>
</tr>
</table>
我真的无法发现我的细节组件有什么问题???提前感谢您的帮助!
【问题讨论】:
标签: typescript angular