【问题标题】:angular 2 - display result of GET in consoleangular 2 - 在控制台中显示 GET 的结果
【发布时间】:2016-12-14 00:53:02
【问题描述】:

我一直在修改英雄教程,遇到了一些我不明白的地方,希望有人能提供帮助。

在 HeroesComponent.ts 中是这段 sn-p 代码

export class HeroesComponent implements OnInit {

 heroes: Hero[];
 selectedHero: Hero;

  constructor(private router: Router, private heroService: HeroService) { }

 getHeroes(): void {
    this.heroService.getHeroes().then(heroes => this.heroes = heroes);
  }

  ngOnInit(): void {
    this.getHeroes();
  }

 onSelect(hero: Hero): void {
  this.selectedHero = hero;
 }

这很有效 - 英雄名称显示在相应的 html 中。

但是,在 getHeroes() 中,如果我添加一个控制台语句

getHeroes(): void {
    this.heroService.getHeroes().then(heroes => this.heroes = heroes);
  console.log("heroes list is " + this.heroes)
  }

然后浏览器控制台显示“英雄列表未定义”,但是在html中显示了英雄数组。

为什么没有定义英雄?

【问题讨论】:

    标签: angular


    【解决方案1】:

    因为console是同步的,get是异步的,所以数组是未定义的

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-23
      • 2015-03-12
      • 1970-01-01
      • 2023-02-25
      • 2020-10-20
      相关资源
      最近更新 更多