Walter Sung Walter Sung - 4 days ago 5
HTTP Question

Understanding HTTP in Angular 2 tutorial

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?

Answer

It's definitely not magic.

What's happening is you're calling a get request to a in memory api !

Have a look at in-memory-api

Basically , the class InMemoryDataService , extends from a InMemoryDbService which creates a in memory api observable .

Think of it as a stub that has been created on the fly and then when you call get method the call will be redirected to that package (via xhrbackend) and then you get that hero list . .

Comments