DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Coding
  3. Frameworks
  4. Learning Angular 2: Tour of Heroes Tutorial, HTTP

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.

Brian Swartzfager user avatar by
Brian Swartzfager
·
Aug. 22, 16 · Tutorial
Like (2)
Save
Tweet
Share
5.26K Views

Join the DZone community and get the full member experience.

Join For Free

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:

//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';


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() } )
    .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.

AngularJS Object (computer science)

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

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • How Chat GPT-3 Changed the Life of Young DevOps Engineers
  • A Beginner's Guide to Infrastructure as Code
  • Create a CLI Chatbot With the ChatGPT API and Node.js
  • How To Set Up and Run Cypress Test Cases in CI/CD TeamCity

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: