我正在使用Hero App进行Angular 2教程.我是本教程的Http部分.(链接)
在hero.service.ts中使用以下方法调用服务器
getHeroes(): Promise<Hero[]> {
return this.http.get(this.heroesUrl)
.toPromise()
.then(response => response.json().data)
.catch(this.handleError);
}
Run Code Online (Sandbox Code Playgroud)
然后我试图在下面的heroes.components.ts中使用返回的数据,但我无法正确实现then函数.我收到此控制台错误
EXCEPTION:错误:未捕获(在承诺中):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();
}
Run Code Online (Sandbox Code Playgroud)
你知道为什么我不能console.log this.heroes和title?
您可能需要考虑使用胖箭头符号来避免范围冲突.在您的情况下,这不是指向类实例,而是指向您的承诺的sucesscallback.
getHeroes() {
let instance : HeroesComponent = this;
this.heroService.getHeroes().then((value) => {
//SUCCESS
console.log(value);
this.heroes = value;
console.log("I am inside then SUCCESS")
console.log(this.title);
console.log(this.heroes);
}, (error) => {
//FAILURE
console.log(error);
})
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15187 次 |
| 最近记录: |