I've been going through the Angular 2 Tour of Heroes tutorial and I'm not understanding the lesson on using HTTP to fetch data from a service.
In this lesson in the Hero Service a variable heroesUrl is declared as 'app/heroes'.
private heroesUrl = 'app/heroes'; // URL to web api
constructor(private http: Http) { }
getHeroes(): Promise<Hero[]> {
return this.http.get(this.heroesUrl)
.toPromise()
.then(response => response.json().data as Hero[])
.catch(this.handleError);
}
The data is declared in the in-memory-data service as a static array:
import { InMemoryDbService } from 'angular-in-memory-web-api';
export class InMemoryDataService implements InMemoryDbService {
createDb() {
let heroes = [
{ id: 11, name: 'Mr. Nice (api)' },
{ id: 12, name: 'Narco' },
{ id: 13, name: 'Bombasto' },
{ id: 14, name: 'Celeritas' },
{ id: 15, name: 'Magneta' },
{ id: 16, name: 'RubberMan' },
{ id: 17, name: 'Dynama' },
{ id: 18, name: 'Dr IQ' },
{ id: 19, name: 'Magma' },
{ id: 20, name: 'Tornado' },
{ id: 21, name: 'Mister Man' }
];
return { heroes };
}
}
But in the routing module 'heroes' (which I assume is the same as 'app/heroes') points to the HeroesComponent.
const routes: Routes = [
{ path: '', redirectTo: '/dashboard', pathMatch: 'full' },
{ path: 'dashboard', component: DashboardComponent },
{ path: 'detail/:id', component: HeroDetailComponent },
{ path: 'heroes', component: HeroesComponent }
];
In the HeroesComponent the getHeroes() function calls the this.heroService.getHeroes() function:
getHeroes(): void {
//Result of heroService.getHeroes is a Promise
this.heroService.getHeroes().then(heroesresult => this.heroes = heroesresult);
}
On the surface it looks like HeroesComponent.getHeroes() calls HeroService.getHeroes() which then does a http.get back to the HeroesComponent, not to the data source.
It all works for me (like magic) but there is no explanation of how the data which is in the in-memory-data service is fetched by the call from HeroesService to this.http.get(this.heroesUrl).
Could somebody please help me understand?
private heroesUrl = 'app/heroes'; // URL to web api, that just a simulation url, when you develop your own app, just replace that url by your url