【发布时间】:2016-07-15 06:56:39
【问题描述】:
我正在使用 Hero 应用程序编写 Angular 2 教程。我在教程的 Http 部分。 (link)
在 hero.service.ts 中有如下方法调用服务端
getHeroes(): Promise<Hero[]> {
return this.http.get(this.heroesUrl)
.toPromise()
.then(response => response.json().data)
.catch(this.handleError);
}
然后我尝试在下面的 heros.components.ts 中使用返回的数据,但我无法正确实现 then 函数。我收到此控制台错误
异常:错误:未捕获(在承诺中):TypeError:这是 null
export class HeroesComponent implements OnInit {
title = 'Tour of Heroes';
heroes: Hero[];
selectedHero: Hero;
constructor(
private router: Router,
private heroService: HeroService) { }
getHeroes() {
this.heroService.getHeroes().then(function(value) {
//SUCCESS
console.log(value); //this is working
this.heroes = value; //this is not working
console.log("I am inside then SUCCESS")
console.log(title);
console.log(this.heroes);
}, function(error) {
//FAILURE
console.log(error);
})
}
ngOnInit() {
this.getHeroes();
}
你知道为什么我不能 console.log this.heroes 和 title 吗?
【问题讨论】: