Learning Angular 2: Tour of Heroes Tutorial, HTTP

Datetime:2016-08-22 22:57:31          Topic: AngularJS           Share

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:

//in-memory-data.service.ts

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

private heroesUrl = 'app/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() } )
    .toPromise()
    .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.





About List