If you look at the hero-list.component.ts
:
ngOnInit() {
this._service.getHeroes().then(heroes => this.heroes = heroes)
}
They are calling the service method getHeroes
which returns a Promise
and following that, they call the then
method on that returned promise, including the callback that tells the promise object what to do once it gets resolved.
In the hero.service.ts
they have the heroes
as a local array and they don't have to do a server call, but in a real app you won't have this data here, you'd call a remote server for that data, so if you would return the Array directly instead of a wrapping it with a Promise, in the future when you change the service to call to a real http method you'd have to change both the service and all the components that use it, to receive a Promise instead of an Array.
By wrapping the local Array into a Promise you can make sure that the code on the component will already work with a Promise, so it doesn't matter if that promise gets resolved syncronously or asyncronously, nor you care, it'll work correctly on both scenarios, so you can start out by testing your services with locally mocked data, return that data wrapped into Promises and change them later on into real http calls only by modifying the Services without touching all the components that use that Service.