I'm following along with the tutorial instructions for Angular2 here: https://angular.io/docs/ts/latest/tutorial/toh-pt4.html
At one point, it notes that to return the service's promise information back to the component, the following syntax is required:
getHeroes() {
this._heroService.getHeroes().then(heroes => this.heroes = heroes);
}
I'm trying to understand exactly what's happening here, though I'm new to Angular2 and TypeScript. The documentation says:
Our callback sets the component's heroes property to the array of heroes returned by the service.
I'm confused about what's going on in the parentheses, and specifically, where the final "heroes" is coming from. The service, so far as I can tell, doesn't return "heroes." Instead it imports and returns HEROES from mock-heroes, which itself uses the Heroes interface and returns the HEROES array. I don't see "heroes" (lower case) in any of this.
Is "heroes" being created on the fly? Can someone explain in a little more detail what each part of:
heroes => this.heroes = heroes
does? Thanks so much.
The first thing to bear in mind is that the method heroService.getHeroes()
does not return heroes, but a promise that will eventually resolve, returning a list of heroes:
getHeroes() {
return Promise.resolve(HEROES);
}
Lets then dissect a bit this line of code:
this._heroService.getHeroes().then(heroes => this.heroes = heroes);
This could also have been written in the following way:
this._heroService.getHeroes().then(function(heroesFromPromise) {
this.heroes = heroesFromPromise;
});
This means, call the _heroService.getHeroes()
method, which returns a promise. When the promise resolves, the callback inside then
is called with the result of the promise.
When that happens execute the callback is called that takes the output of the promise (heroesPromise
), and assigns it to the this.heroes
member variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With