On Tuesday, December 13, 2016 at 8:22:49 PM UTC+5:45, norricorp wrote:
>
> Hi,
> I have been amending the heroes tutorial and come across something that I
> do not understand so hopefully some one can help.
>
> In HeroesComponent.ts is this snippet of code
>
> 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;
> }
>
> And this works - the hero names are displayed to the corresponding html.
>
> But, in getHeroes(), if I add a console statement
>
> getHeroes(): void {
> this.heroService.getHeroes().then(heroes => this.heroes = heroes);
> console.log("heroes list is " + this.heroes)
> }
>
> Then the browser console shows "heroes list is undefined", yet the array
> of hero is displayed in the html.
>
> Why is heroes undefined?
>
Heroes are undefined because Console statement
executes before the heroes content are retrieved from the service. Since
angular is asynchronous, the functions are synchronous,
--
You received this message because you are subscribed to the Google Groups
"Angular" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.