Over a million developers have joined DZone.

Learning Angular 2: Tour of Heroes Tutorial, HTTP

DZone's Guide to

Learning Angular 2: Tour of Heroes Tutorial, HTTP

The final lesson of the Tour of Heroes tutorial covers using Angular 2 with HTTP. Check out author Brian Swartzfager's take on the tutorial.

· Web Dev Zone
Free Resource

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

The final lesson of the Tour of Heroes tutorial covers using Angular 2 with HTTP.

It starts off with what seems to be a bit of a contradiction: it shows how to add the set of HTTP services to the application via the bootstrap invocation in main.ts (following the pattern set to add the router), but then makes a point of mentioning that usually application-wide services are registered in the AppComponent providers (HeroService being the prime example in the tutorial up to this point). The implication seems to be that if we didn't need to mock the HTTP transactions because we have no actual server to talk with, we could register HTTP_PROVIDERS in the AppComponent, but I wish they had said that explicitly.

The revisions to the HeroService to utilize HTTP calls start with a revision that includes adding "HTTP" to the new constructor method, but leaves out mentioning the need to import HTTP into the file. Same with the Headers class used in the new service methods for updating heroes, so HeroService needs the following imports:

import { Headers, Http } from '@angular/http';

Interesting how the import of the RxJS toPromise() operator is not imported with a variable reference like the rest of the imports.

One thing that's not explained in the lesson is the relationship between the heroesUrl ( 'app/heroes') and the array of heroes in the in-memory-data.service.ts file. According to the in-memory web API documentation, the latter half of the "URL" in this particular call references a key name created in the createDB() method that refers to an array of objects. So changing the HeroService to call from a list of monsters instead of heroes is as easy as:


createDb() {
  //…The heroes array in the lesson
  let monsters = [
    {id: 11, name: 'Mr. Munch Munch'},
    {id: 12, name: 'Grumpy Pants'},
  return { heroes, monsters };


private heroesUrl = 'app/monsters';

Image of list of monsters

And you can target an individual object in the data array by id value, as is done in the put() and delete() methods described in the lesson. I wondered though if that meant you were locked into a convention of having an "id" property, so I looked around and found the GitHub page for the in-memory-web-api, which said you could specify the property name to use as the identifier as well as the value ("id" apparently being the default property name if none is specified). I couldn't get the example syntax where the property name was preceded by a "?" (so maybe the documentation is a tad out-of-date), but I could create a URL targeting a Hero by name instead of id without the "?":

let url = `${this.heroesUrl}/name=${hero.name}`;

The need to add the Content-Type header to every add, update, and delete action to specify the use of JSON caught my eye. It makes sense given the HTTP methods take an array of headers as an argument, but I could see making a private function that would handle creating and returning that headers array that the HTTP functions could all share. Like so:

private getHeaders(): Headers {
  let headers = new Headers();
  headers.append( 'Content-Type', 'application/json' );
  return headers;
private put(hero: Hero) {
  let url = `${this.heroesUrl}/${hero.id}`;

  return this.http
    .put( url, JSON.stringify( hero ), { headers: this.getHeaders() } )
    .then( () => hero )
    .catch( this.handleError );

The next step of the lesson involves updating the code of the HeroDetailComponent to invoke the public save() method on the HeroService (which calls either the put() or post() private service methods as appropriate).  I don't know why the @Input decorator is applied to the hero property of HeroDetailComponent:  while it's true that later in the lesson HeroDetailComponent is once again made a subcomponent of the HeroComponent, the HeroComponent never passes a Hero object to HeroDetailComponent, and removing the @Input decorator doesn't break any of the new add, update, and delete functionality.

The @Output decorator and the "close" EventEmitter object are a different story.  At first, when I was simply following along with the lesson, I didn't pick up on exactly how the HeroComponent knew to listen for the emission of the saved Hero object that occurs in the HeroDetailComponent goBack() method.  The HeroComponent is coded to react to the "close" EventEmitter of HeroDetailComponent through the event handler put on the directive:

<my-hero-detail (close)="close($event)"></my-hero-detail>

I find it interesting that the argument passed to the close() method of HeroComponent is "$event", and yet what the goBack() method emits and what the close() method expects as its argument is a Hero object. If I change the argument name in the directive from $event to something else, like "sentHero", the incoming argument in the close() method ends up as undefined. In contrast, the delete event handler in HeroComponent passes both a Hero object and an $event object to the HeroComponent deleteHero() method.

The lesson neglects to mention the need to define a Boolean "addingHero" property to the HeroComponent, but of course an IDE like IntelliJ is quick to point that out.

The delete() method of the HeroService starts with an "event.stopPropagation()" statement.  The lesson doesn't explicitly explain why, but the reason it's there is because the delete button in the UI is contained within each hero <li> block, which all have a click event handler that sets the selected hero.  So the stopPropagation prevents the invocation of the click event that would briefly display the mini-detail UI for the selected hero prior to deletion.

This lesson marks the end of the Tour of Heroes tutorial in its current form.  Overall, I thought it was an excellent introduction to the basic elements involved in creating an application with Angular 2.  I was surprised that it didn't include a lesson on forms, but a quick glance at the overall documentation implies that the forms API is still evolving.  I'll have to explore that on my own in the near future.

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

handler ,service ,methods ,constructor ,tutorial ,event ,object

Published at DZone with permission of Brian Swartzfager, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}