docs:(TOH chapter on Http) New Tour of Hero Chapter on Http

This commit is contained in:
Torgeir Helgevold 2016-04-09 00:18:37 -04:00 committed by Ward Bell
parent 31fe01e01f
commit e4db340464
28 changed files with 1096 additions and 3 deletions

View File

@ -23,8 +23,8 @@ import { HeroService } from './hero.service';
</ul>
<my-hero-detail [hero]="selectedHero"></my-hero-detail>
`,
// #enddocregion template
styles:[`
// #enddocregion template
styles: [`
.selected {
background-color: #CFD8DC !important;
color: white;

View File

@ -3,12 +3,12 @@
import { Component } from '@angular/core';
import { RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from '@angular/router-deprecated';
import { HeroService } from './hero.service';
import { DashboardComponent } from './dashboard.component';
import { HeroesComponent } from './heroes.component';
// #docregion hero-detail-import
import { HeroDetailComponent } from './hero-detail.component';
// #enddocregion hero-detail-import
import { HeroService } from './hero.service';
@Component({
selector: 'my-app',

View File

@ -0,0 +1,133 @@
describe('TOH Http Chapter', function () {
beforeEach(function () {
browser.get('');
});
function getPageStruct() {
hrefEles = element.all(by.css('my-app a'));
return {
hrefs: hrefEles,
myDashboardHref: hrefEles.get(0),
myDashboardParent: element(by.css('my-app my-dashboard')),
topHeroes: element.all(by.css('my-app my-dashboard .module.hero')),
myHeroesHref: hrefEles.get(1),
myHeroesParent: element(by.css('my-app my-heroes')),
allHeroes: element.all(by.css('my-app my-heroes li .hero-element')),
firstDeleteButton: element.all(by.buttonText('Delete')).get(0),
addButton: element.all(by.buttonText('Add New Hero')).get(0),
heroDetail: element(by.css('my-app my-hero-detail'))
}
}
it('should be able to add a hero from the "Heroes" view', function(){
var page = getPageStruct();
var heroCount;
page.myHeroesHref.click().then(function() {
browser.waitForAngular();
heroCount = page.allHeroes.count();
expect(heroCount).toBe(4, 'should show 4');
}).then(function() {
return page.addButton.click();
}).then(function(){
return save(page,'','The New Hero');
}).then(function(){
browser.waitForAngular();
heroCount = page.allHeroes.count();
expect(heroCount).toBe(5, 'should show 5');
var newHero = element(by.xpath('//span[@class="hero-element" and contains(text(),"The New Hero")]'));
expect(newHero).toBeDefined();
});
});
it('should be able to delete hero from "Heroes" view', function(){
var page = getPageStruct();
var heroCount;
page.myHeroesHref.click().then(function() {
browser.waitForAngular();
heroCount = page.allHeroes.count();
expect(heroCount).toBe(4, 'should show 4');
}).then(function() {
return page.firstDeleteButton.click();
}).then(function(){
browser.waitForAngular();
heroCount = page.allHeroes.count();
expect(heroCount).toBe(3, 'should show 3');
});
});
it('should be able to save details from "Dashboard" view', function () {
var page = getPageStruct();
expect(page.myDashboardParent.isPresent()).toBe(true, 'dashboard element should be available');
var heroEle = page.topHeroes.get(2);
var heroDescrEle = heroEle.element(by.css('h4'));
var heroDescr;
return heroDescrEle.getText().then(function(text) {
heroDescr = text;
return heroEle.click();
}).then(function() {
return save(page, heroDescr, '-foo');
})
.then(function(){
return page.myDashboardHref.click();
})
.then(function() {
expect(page.myDashboardParent.isPresent()).toBe(true, 'dashboard element should be back');
expect(heroDescrEle.getText()).toEqual(heroDescr + '-foo');
});
});
it('should be able to save details from "Heroes" view', function () {
var page = getPageStruct();
var viewDetailsButtonEle = page.myHeroesParent.element(by.cssContainingText('button', 'View Details'));
var heroEle, heroDescr;
page.myHeroesHref.click().then(function() {
expect(page.myDashboardParent.isPresent()).toBe(false, 'dashboard element should NOT be present');
expect(page.myHeroesParent.isPresent()).toBe(true, 'myHeroes element should be present');
expect(viewDetailsButtonEle.isPresent()).toBe(false, 'viewDetails button should not yet be present');
heroEle = page.allHeroes.get(0);
return heroEle.getText();
}).then(function(text) {
// remove leading 'id' from the element
heroDescr = text.substr(text.indexOf(' ')+1);
return heroEle.click();
}).then(function() {
expect(viewDetailsButtonEle.isDisplayed()).toBe(true, 'viewDetails button should now be visible');
return viewDetailsButtonEle.click();
}).then(function() {
return save(page, heroDescr, '-bar');
})
.then(function(){
return page.myHeroesHref.click();
})
.then(function() {
expect(heroEle.getText()).toContain(heroDescr + '-bar');
});
});
function save(page, origValue, textToAdd) {
var inputEle = page.heroDetail.element(by.css('input'));
expect(inputEle.isDisplayed()).toBe(true, 'should be able to see the input box');
var saveButtonEle = page.heroDetail.element(by.buttonText('Save'));
var backButtonEle = page.heroDetail.element(by.buttonText('Back'));
expect(backButtonEle.isDisplayed()).toBe(true, 'should be able to see the back button');
var detailTextEle = page.heroDetail.element(by.css('div h2'));
expect(detailTextEle.getText()).toContain(origValue);
return sendKeys(inputEle, textToAdd).then(function () {
expect(detailTextEle.getText()).toContain(origValue + textToAdd);
return saveButtonEle.click();
});
}
});

View File

@ -0,0 +1 @@
**/*.js

View File

@ -0,0 +1,31 @@
/* #docplaster */
/* #docregion css */
h1 {
font-size: 1.2em;
color: #999;
margin-bottom: 0;
}
h2 {
font-size: 2em;
margin-top: 0;
padding-top: 0;
}
nav a {
padding: 5px 10px;
text-decoration: none;
margin-top: 10px;
display: inline-block;
background-color: #eee;
border-radius: 4px;
}
nav a:visited, a:link {
color: #607D8B;
}
nav a:hover {
color: #039be5;
background-color: #CFD8DC;
}
nav a.router-link-active {
color: #039be5;
}
/* #enddocregion css */

View File

@ -0,0 +1,36 @@
// #docplaster
// #docregion
import { Component } from '@angular/core';
import { RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from '@angular/router-deprecated';
import { DashboardComponent } from './dashboard.component';
import { HeroesComponent } from './heroes.component';
import { HeroDetailComponent } from './hero-detail.component';
import { HeroService } from './hero.service';
@Component({
selector: 'my-app',
template: `
<h1>{{title}}</h1>
<nav>
<a [routerLink]="['Dashboard']">Dashboard</a>
<a [routerLink]="['Heroes']">Heroes</a>
</nav>
<router-outlet></router-outlet>
`,
styleUrls: ['app/app.component.css'],
directives: [ROUTER_DIRECTIVES],
providers: [
ROUTER_PROVIDERS,
HeroService,
]
})
@RouteConfig([
{ path: '/dashboard', name: 'Dashboard', component: DashboardComponent, useAsDefault: true },
{ path: '/detail/:id', name: 'HeroDetail', component: HeroDetailComponent },
{ path: '/heroes', name: 'Heroes', component: HeroesComponent }
])
export class AppComponent {
title = 'Tour of Heroes';
}

View File

@ -0,0 +1,63 @@
/* #docplaster */
/* #docregion */
[class*='col-'] {
float: left;
}
*, *:after, *:before {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
h3 {
text-align: center; margin-bottom: 0;
}
[class*='col-'] {
padding-right: 20px;
padding-bottom: 20px;
}
[class*='col-']:last-of-type {
padding-right: 0;
}
.grid {
margin: 0;
}
.col-1-4 {
width: 25%;
}
.module {
padding: 20px;
text-align: center;
color: #eee;
max-height: 120px;
min-width: 120px;
background-color: #607D8B;
border-radius: 2px;
}
h4 {
position: relative;
}
.module:hover {
background-color: #EEE;
cursor: pointer;
color: #607d8b;
}
.grid-pad {
padding: 10px 0;
}
.grid-pad > [class*='col-']:last-of-type {
padding-right: 20px;
}
@media (max-width: 600px) {
.module {
font-size: 10px;
max-height: 75px; }
}
@media (max-width: 1024px) {
.grid {
margin: 0;
}
.module {
min-width: 60px;
}
}
/* #enddocregion */

View File

@ -0,0 +1,11 @@
<!-- #docregion -->
<h3>Top Heroes</h3>
<div class="grid grid-pad">
<!-- #docregion click -->
<div *ngFor="let hero of heroes" (click)="gotoDetail(hero)" class="col-1-4">
<!-- #enddocregion click -->
<div class="module hero">
<h4>{{hero.name}}</h4>
</div>
</div>
</div>

View File

@ -0,0 +1,32 @@
// #docplaster
// #docregion
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router-deprecated';
import { Hero } from './hero';
import { HeroService } from './hero.service';
@Component({
selector: 'my-dashboard',
templateUrl: 'app/dashboard.component.html',
styleUrls: ['app/dashboard.component.css']
})
export class DashboardComponent implements OnInit {
heroes: Hero[] = [];
constructor(
private _router: Router,
private _heroService: HeroService) {
}
ngOnInit() {
this._heroService.getHeroes()
.then(heroes => this.heroes = heroes.slice(1,5));
}
gotoDetail(hero: Hero) {
let link = ['HeroDetail', { id: hero.id }];
this._router.navigate(link);
}
}

View File

@ -0,0 +1,30 @@
/* #docregion */
label {
display: inline-block;
width: 3em;
margin: .5em 0;
color: #607D8B;
font-weight: bold;
}
input {
height: 2em;
font-size: 1em;
padding-left: .4em;
}
button {
margin-top: 20px;
font-family: Arial;
background-color: #eee;
border: none;
padding: 5px 10px;
border-radius: 4px;
cursor: pointer; cursor: hand;
}
button:hover {
background-color: #cfd8dc;
}
button:disabled {
background-color: #eee;
color: #ccc;
cursor: auto;
}

View File

@ -0,0 +1,13 @@
<!-- #docplaster -->
<!-- #docregion -->
<div *ngIf="hero">
<h2>{{hero.name}} details!</h2>
<div>
<label>id: </label>{{hero.id}}</div>
<div>
<label>name: </label>
<input [(ngModel)]="hero.name" placeholder="name" />
</div>
<button (click)="goBack()">Back</button>
<button (click)="save()">Save</button>
</div>

View File

@ -0,0 +1,53 @@
// #docplaster
// #docregion
import { Component, Input, Output, OnInit, EventEmitter } from '@angular/core';
import { RouteParams } from '@angular/router-deprecated';
import { Hero } from './hero';
import { HeroService } from './hero.service';
@Component({
selector: 'my-hero-detail',
templateUrl: 'app/hero-detail.component.html',
styleUrls: ['app/hero-detail.component.css']
})
export class HeroDetailComponent implements OnInit {
@Input() hero: Hero;
@Output() close = new EventEmitter();
error: any;
navigated = false; // true if navigated here
constructor(
private _heroService: HeroService,
private _routeParams: RouteParams) {
}
// #docregion ngOnInit
ngOnInit() {
if (this._routeParams.get('id') !== null) {
let id = +this._routeParams.get('id');
this.navigated = true;
this._heroService.getHero(id)
.then(hero => this.hero = hero);
} else {
this.navigated = false;
this.hero = new Hero();
}
}
// #enddocregion ngOnInit
// #docregion save
save() {
this._heroService
.save(this.hero)
.then(hero => {
this.hero = hero; // saved hero, w/ id if new
this.goBack(hero);
})
.catch(error => this.error = error); // TODO: Display error message
}
// #enddocregion save
goBack(savedHero: Hero = null) {
this.close.emit(savedHero);
if (this.navigated) { window.history.back(); }
}
}

View File

@ -0,0 +1,99 @@
// #docplaster
// #docregion
import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
// #docregion rxjs
import 'rxjs/add/operator/toPromise';
// #enddocregion rxjs
import { Hero } from './hero';
@Injectable()
export class HeroService {
private heroesUrl = 'app/heroes'; // URL to web api
constructor(private http: Http) { }
// #docregion get-heroes
getHeroes(): Promise<Hero[]> {
return this.http.get(this.heroesUrl)
// #docregion to-promise
.toPromise()
// #enddocregion to-promise
// #docregion to-data
.then(response => response.json().data)
// #enddocregion to-data
// #docregion catch
.catch(this.handleError);
// #enddocregion catch
}
// #enddocregion get-heroes
getHero(id: number) {
return this.getHeroes()
.then(heroes => heroes.filter(hero => hero.id === id)[0]);
}
// #docregion save
save(hero: Hero): Promise<Hero> {
if (hero.id) {
return this.put(hero);
}
return this.post(hero);
}
// #enddocregion save
// #docregion delete-hero
delete(hero: Hero) {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let url = `${this.heroesUrl}/${hero.id}`;
return this.http
.delete(url, headers)
.toPromise()
.catch(this.handleError);
}
// #enddocregion delete-hero
// #docregion post-hero
// Add new Hero
private post(hero: Hero): Promise<Hero> {
let headers = new Headers({
'Content-Type': 'application/json'});
return this.http
.post(this.heroesUrl, JSON.stringify(hero), {headers: headers})
.toPromise()
.then(res => res.json().data)
.catch(this.handleError);
}
// #enddocregion post-hero
// #docregion put-hero
// Update existing Hero
private put(hero: Hero) {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let url = `${this.heroesUrl}/${hero.id}`;
return this.http
.put(url, JSON.stringify(hero), {headers: headers})
.toPromise()
.then(() => hero)
.catch(this.handleError);
}
// #enddocregion put-hero
// #docregion error-handler
private handleError(error: any) {
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
// #enddocregion error-handler
}
// #enddocregion

View File

@ -0,0 +1,4 @@
export class Hero {
id: number;
name: string;
}

View File

@ -0,0 +1,59 @@
.selected {
background-color: #CFD8DC !important;
color: white;
}
.heroes {
margin: 0 0 2em 0;
list-style-type: none;
padding: 0;
width: 15em;
}
.heroes li {
cursor: pointer;
position: relative;
left: 0;
background-color: #EEE;
margin: .5em;
padding: .3em 0;
height: 1.6em;
border-radius: 4px;
}
.heroes li:hover {
color: #607D8B;
background-color: #DDD;
left: .1em;
}
.heroes li.selected:hover {
background-color: #BBD8DC !important;
color: white;
}
.heroes .text {
position: relative;
top: -3px;
}
.heroes .badge {
display: inline-block;
font-size: small;
color: white;
padding: 0.8em 0.7em 0 0.7em;
background-color: #607D8B;
line-height: 1em;
position: relative;
left: -1px;
top: -4px;
height: 1.8em;
margin-right: .8em;
border-radius: 4px 0 0 4px;
}
button {
font-family: Arial;
background-color: #eee;
border: none;
padding: 5px 10px;
border-radius: 4px;
cursor: pointer;
cursor: hand;
}
button:hover {
background-color: #cfd8dc;
}

View File

@ -0,0 +1,21 @@
<!-- #docregion -->
<h2>My Heroes</h2>
<ul class="heroes">
<li *ngFor="let hero of heroes" (click)="onSelect(hero)" [class.selected]="hero === selectedHero">
<span class="hero-element">
<span class="badge">{{hero.id}}</span> {{hero.name}}
</span>
<button class="delete-button" (click)="delete(hero, $event)">Delete</button>
</li>
</ul>
<button (click)="addHero()">Add New Hero</button>
<div *ngIf="addingHero">
<my-hero-detail (close)="close($event)"></my-hero-detail>
</div>
<div *ngIf="selectedHero">
<h2>
{{selectedHero.name | uppercase}} is my hero
</h2>
<button (click)="gotoDetail()">View Details</button>
</div>

View File

@ -0,0 +1,66 @@
// #docregion
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router-deprecated';
import { Hero } from './hero';
import { HeroDetailComponent } from './hero-detail.component';
import { HeroService } from './hero.service';
@Component({
selector: 'my-heroes',
templateUrl: 'app/heroes.component.html',
styleUrls: ['app/heroes.component.css'],
directives: [HeroDetailComponent]
})
export class HeroesComponent implements OnInit {
heroes: Hero[];
selectedHero: Hero;
addingHero = false;
error: any;
constructor(
private _router: Router,
private _heroService: HeroService) { }
getHeroes() {
this._heroService
.getHeroes()
.then(heroes => this.heroes = heroes)
.catch(error => this.error = error); // TODO: Display error message
}
addHero() {
this.addingHero = true;
this.selectedHero = null;
}
close(savedHero: Hero) {
this.addingHero = false;
if (savedHero) { this.getHeroes(); }
}
// #docregion delete
delete(hero: Hero, event: any) {
event.stopPropagation();
this._heroService
.delete(hero)
.then(res => {
this.heroes = this.heroes.filter(h => h.id !== hero.id);
})
.catch(error => this.error = error); // TODO: Display error message
}
// #enddocregion delete
ngOnInit() {
this.getHeroes();
}
onSelect(hero: Hero) {
this.selectedHero = hero;
this.addingHero = false;
}
gotoDetail() {
this._router.navigate(['HeroDetail', { id: this.selectedHero.id }]);
}
}

View File

@ -0,0 +1,12 @@
// #docregion
export class InMemoryDataService {
createDb() {
let heroes = [
{ id: 1, name: 'Windstorm' },
{ id: 2, name: 'Bombasto' },
{ id: 3, name: 'Magneta' },
{ id: 4, name: 'Tornado' }
];
return {heroes};
}
}

View File

@ -0,0 +1,29 @@
// #docplaster
// #docregion final
// Imports for loading & configuring the in-memory web api
import { provide } from '@angular/core';
import { XHRBackend } from '@angular/http';
import { InMemoryBackendService, SEED_DATA } from 'angular2-in-memory-web-api/core';
import { InMemoryDataService } from './in-memory-data.service';
// The usual bootstrapping imports
// #docregion v1
import { bootstrap } from '@angular/platform-browser-dynamic';
import { HTTP_PROVIDERS } from '@angular/http';
import { AppComponent } from './app.component';
// #enddocregion v1, final
/*
// #docregion v1
bootstrap(AppComponent, [ HTTP_PROVIDERS ]);
// #enddocregion v1
*/
// #docregion final
bootstrap(AppComponent, [
HTTP_PROVIDERS,
provide(XHRBackend, { useClass: InMemoryBackendService }), // in-mem server
provide(SEED_DATA, { useClass: InMemoryDataService }) // in-mem server data
]);
// #enddocregion final

View File

@ -0,0 +1,27 @@
<!DOCTYPE html>
<html>
<head>
<base href="/">
<title>Angular 2 Tour of Heroes</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<link rel="stylesheet" href="sample.css">
<!-- Polyfill(s) for older browsers -->
<script src="node_modules/es6-shim/es6-shim.min.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/reflect-metadata/Reflect.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="systemjs.config.js"></script>
<script>
System.import('app').catch(function(err){ console.error(err); });
</script>
</head>
<body>
<my-app>Loading...</my-app>
</body>
</html>

View File

@ -0,0 +1,9 @@
{
"description": "Tour of Heroes: Part 6",
"files":[
"!**/*.d.ts",
"!**/*.js",
"!**/*.[1,2].*"
],
"tags": ["tutorial", "tour", "heroes", "http"]
}

View File

@ -0,0 +1,8 @@
button.delete-button{
float:right;
background-color: gray !important;
color:white;
}

View File

@ -29,5 +29,10 @@
"title": "Routing",
"intro": "We add the Angular Component Router and learn to navigate among the views",
"nextable": true
},
"toh-pt6": {
"title": "Http",
"intro": "We convert our service and components to use Http",
"nextable": true
}
}

View File

@ -669,6 +669,7 @@ figure.image-display
.file index.html
.file package.json
.file styles.css
.file systemjs.config.json
.file tsconfig.json
.file typings.json
:marked

View File

@ -0,0 +1,350 @@
include ../_util-fns
:marked
# Http
Our application has become a huge success and our stakeholders have expanded the vision to include integration with a hero api.
The current solution limits us to a fixed set of heroes, but integration with a web server api will make our application much more flexible. We will also be able to add, edit and delete heroes.
In this chapter we will connect our Angular 2 services to make http calls to our new api.
:marked
[Run the live example](/resources/live-examples/toh-6/ts/plnkr.html).
.l-main-section
:marked
## Where We Left Off
Before we continue with our Tour of Heroes, lets verify that we have the following structure after adding our hero service
and hero detail component. If not, well need to go back and follow the previous chapters.
.filetree
.file angular2-tour-of-heroes
.children
.file app
.children
.file app.component.ts
.file app.component.css
.file dashboard.component.css
.file dashboard.component.html
.file dashboard.component.ts
.file hero.ts
.file hero-detail.component.css
.file hero-detail.component.html
.file hero-detail.component.ts
.file hero.service.ts
.file heroes.component.css
.file heroes.component.html
.file heroes.component.ts
.file main.ts
.file mock-heroes.ts
.file node_modules ...
.file typings ...
.file index.html
.file package.json
.file styles.css
.file systemjs.config.json
.file tsconfig.json
.file typings.json
:marked
### Keep the app transpiling and running
Open a terminal/console window and enter the following command to
start the TypeScript compiler, start the server, and watch for changes:
code-example(format="." language="bash").
npm start
:marked
The application runs and updates automatically as we continue to build the Tour of Heroes.
.l-main-section
:marked
## Prepare for Http
`Http` is ***not*** a core Angular module.
It's Angular's optional approach to web access and it exists as a separate add-on module called `@angular/http`,
shipped in a separate script file as part of the Angular npm package.
Fortunately we're ready to import from `@angular/http` because `systemjs.config` configured *SystemJS* to load that library when we need it.
:marked
### Register (provide) *http* services
Our app will depend upon the Angular `http` service which itself depends upon other supporting services.
The `HTTP_PROVIDERS` array from `@angular/http` library holds providers for the complete set of http services.
We should be able to access these services from anywhere in the application.
So we register them in the `bootstrap` method of `main.ts` where we
launch the application and its root `AppComponent`.
+makeExample('toh-6/ts/app/main.ts','v1','app/main.ts (v1)')(format='.')
:marked
Notice that we supply the `HTTP_PROVIDERS` in an array as the second parameter to the `bootstrap` method.
This has the same effect the `providers` array in `@Component` metadata.
.l-main-section
:marked
## Simulating the web api
We generally recommend registering application-wide services in the root `AppComponent` *providers*.
Here we're registering in `main` for a special reason.
Our application is in the early stages of development and far from ready for production.
We don't even have a web server that can handle requests for heroes.
Until we do, *we'll have to fake it*.
We're going to *trick* the http client into fetching and saving data from
a demo/development service, the *in-memory web api*.
The application itself doesn't need to know and shouldn't know about this.
So we'll slip the *in-memory web api* into the configuration *above* the `AppComponent`.
Here is a version of `main` that performs this trick
+makeExample('toh-6/ts/app/main.ts', 'final', 'app/main.ts (final)')(format=".")
:marked
We're replacing the default `XHRBackend`, the service that talks to the remote server,
with the *in-memory web api* service after priming it with the following `in-memory-data.service.ts` file:
+makeExample('toh-6/ts/app/in-memory-data.service.ts', null, 'app/in-memory-data.service.ts')(format=".")
:marked
This file replaces the `mock-heroes.ts` which is now safe to delete.
.alert.is-helpful
:marked
This chaper is an introduction to the Angular http client.
Please don't be distracted by the details of this backend substitution. Just follow along with the example.
Learn more later about the *in-memory web api* in the [Http chapter](../guide/server-communication.html#!#in-mem-web-api).
Remember, the *in-memory web api* is only useful in the early stages of development and for demonstrations such as this Tour of Heroes.
Skip it when you have a real web api server.
.l-main-section
:marked
## Heroes and Http
Look at our current `HeroService` implementation
+makeExample('toh-4/ts/app/hero.service.ts', 'get-heroes', 'app/hero.service.ts (getHeroes - old)')(format=".")
:marked
We returned a promise resolved with mock heroes.
It may have seemed like overkill at the time, but we were anticipating the
day when we fetched heroes with an http client and we knew that would have to be an asynchronous operation.
That day has arrived! Let's convert `getHeroes()` to use Angular's `Http` client:
+makeExample('toh-6/ts/app/hero.service.ts', 'get-heroes', 'app/hero.service.ts (getHeroes using Http)')(format=".")
:marked
### Http Promise
We're still returning a promise but we're creating it differently.
The Angular `http.get` returns an RxJS `Observable`.
*Observables* are a powerful way to manage asynchronous data flows.
We'll learn about `Observables` *later*.
For *now* we get back on familiar ground by immediately converting that `Observable` to a `Promise` using the `toPromise` operator.
+makeExample('toh-6/ts/app/hero.service.ts', 'to-promise')(format=".")
:marked
Unfortunately, the Angular `Observable` doesn't have a `toPromise` operator ... not out of the box.
The Angular `Observable` is a bare-bones implementation.
There are scores of operators like `toPromise` that extend `Observable` with useful capabilities.
If we want those capabilities, we have to add the operators ourselves.
That's as easy as importing them from the RxJS library like this:
+makeExample('toh-6/ts/app/hero.service.ts', 'rxjs')(format=".")
:marked
### Extracting the data in the *then* callback
In the *promise*'s `then` callback we call the `json` method of the http `Response` to extract the
data within the response.
+makeExample('toh-6/ts/app/hero.service.ts', 'to-data')(format=".")
:marked
That object returned by `json` has a single `data` property.
The `data` property holds the array of *heroes* that the caller really wants.
So we grab that array and return it as the resolved promise value.
.alert.is-important
:marked
Pay close attention to the shape of the data returned by the server.
This particular *in-memory web api* example happens to return an object with a `data` property.
Your api might return something else.
Adjust the code to match *your web api*.
:marked
The caller is unaware of these machinations. It receives a promise of *heroes* just as it did before.
It has no idea that we fetched the heroes from the server.
It knows nothing of the twists and turns required to turn the http response into heroes.
Such is the beauty and purpose of delegating data access to a service like this `HeroService`.
:marked
### Error Handling
At the end of `getHeroes` we `catch` server failures and pass them to an error handler:
+makeExample('toh-6/ts/app/hero.service.ts', 'catch')(format=".")
:marked
This is a critical step!
We must anticipate http failures as they happen frequently for reasons beyond our control.
+makeExample('toh-6/ts/app/hero.service.ts', 'error-handler', 'app/hero.service.ts (Error handler)')(format=".")
:marked
In this demo service we log the error to the console; we should do better in real life.
We've also decided to return a user friendly form of the error to
to the caller in a rejected promise so that the caller can display a proper error message to the user.
### Promises are Promises
Although we made significant *internal* changes to `getHeroes()`, the public signature did not change.
We still return a promise. We won't have to update any of the components that call `getHeroes()`.
.l-main-section
:marked
## Add, Edit, Delete
Our stakeholders are incredibly pleased with the added flexibility from the api integration, but it doesn't stop there. Next we want to add the capability to add, edit and delete heroes.
We'll complete `HeroService` by creating `post`, `put` and `delete` http calls to meet our new requirements.
:marked
### Post
We are using `post` to add new heroes. Post requests require a little bit more setup than Get requests, but the format is as follows:
+makeExample('toh-6/ts/app/hero.service.ts', 'post-hero', 'app/hero.service.ts (post hero)')(format=".")
:marked
Now we create a header and set the content type to `application/json`. We'll call `JSON.stringify` before we post to convert the hero object to a string.
### Put
`put` is used to edit a specific hero, but the structure is very similar to a `post` request. The only difference is that we have to change the url slightly by appending the id of the hero we want to edit.
+makeExample('toh-6/ts/app/hero.service.ts', 'put-hero', 'app/hero.service.ts (put hero)')(format=".")
:marked
### Delete
`delete` is used to delete heroes and the format is identical to `put` except for the function name.
+makeExample('toh-6/ts/app/hero.service.ts', 'delete-hero', 'app/hero.service.ts (delete hero)')(format=".")
:marked
We add a `catch` to handle our errors for all three cases.
:marked
### Save
We combine the call to the private `_post` and `_put` methods in a single `save` method. This simplifies the public api and makes the integration with `HeroDetailComponent` easier. `HeroService` determines which method to call based on the state of the `hero` object. If the hero already has an id we know it's an edit. Otherwise we know it's an add.
+makeExample('toh-6/ts/app/hero.service.ts', 'save', 'app/hero.service.ts (save hero)')(format=".")
:marked
After these additions our `HeroService` looks like this:
+makeExample('toh-6/ts/app/hero.service.ts', null, 'app/hero.service.ts')(format=".")
.l-main-section
:marked
## Updating Components
Loading heroes using `Http` required no changes outside of `HeroService`, but we added a few new features as well. In the following section we will update our components to use our new methods to add, edit and delete heroes.
### Add/Edit
We already have `HeroDetailComponent` for viewing details about a specific hero. Add and Edit are natural extensions of the detail view, so we are able to reuse `DetailHeroComponent` with a few tweaks. The original component was created to render existing data, but to add new data we have to initialize the `hero` property to an empty `Hero` object.
+makeExample('toh-6/ts/app/hero-detail.component.ts', 'ngOnInit', 'app/hero-detail.component.ts (ngOnInit)')(format=".")
:marked
In order to differentiate between add and edit we are adding a check to see if an id is passed in the url. If the id is absent we bind `HeroDetailComponent` to an empty `Hero` object. In either case, any edits made through the UI will be bound back to the same `hero` property.
The next step is to add a save method to `HeroDetailComponent` and call the corresponding save method in `HeroesService`.
+makeExample('toh-6/ts/app/hero-detail.component.ts', 'save', 'app/hero-detail.component.ts (save)')(format=".")
:marked
The same save method is used for both add and edit since `HeroService` will know when to call `post` vs `put` based on the state of the `Hero` object.
Earlier we used the `save()` method to return a promise, so when the promise resolves, we call `emit` to notify `HeroesComponent` that we just added or modified a hero. `HeroesComponent` is listening for this notification and will automatically refresh the list of heroes to include our recent updates.
.l-sub-section
:marked
The `emit` "handshake" between `HeroDetailComponent` and `HeroesComponent` is an example of component to component communication. This is a topic for another day, but we have detailed information in our <a href="/docs/ts/latest/cookbook/component-communication.html#!#child-to-parent">Component Interaction Cookbook</a>
:marked
Here is `HeroDetailComponent` with the added save button.
figure.image-display
img(src='/resources/images/devguide/toh/hero-details-save-button.png' alt="Hero Details With Save Button")
:marked
### Delete
We have added the option to delete hereos from `HeroesComponent`. `HeroService` will delete the hero, but we still have to filter out the deleted hero from the list to update the view.
+makeExample('toh-6/ts/app/heroes.component.ts', 'delete', 'app/heroes.component.ts (delete)')(format=".")
:marked
Here is `HeroesComponent` with the delete button.
figure.image-display
img(src='/resources/images/devguide/toh/heroes-list-delete-button.png' alt="Heroes List With Delete Button")
:marked
### Review the App Structure
Lets verify that we have the following structure after all of our good refactoring in this chapter:
.filetree
.file angular2-tour-of-heroes
.children
.file app
.children
.file app.component.ts
.file app.component.css
.file dashboard.component.css
.file dashboard.component.html
.file dashboard.component.ts
.file hero.ts
.file hero-detail.component.css
.file hero-detail.component.html
.file hero-detail.component.ts
.file hero.service.ts
.file heroes.component.css
.file heroes.component.html
.file heroes.component.ts
.file main.ts
.file hero-data.service.ts
.file node_modules ...
.file typings ...
.file index.html
.file package.json
.file styles.css
.file sample.css
.file systemjs.config.json
.file tsconfig.json
.file typings.json
.l-main-section
:marked
## Home Stretch
We are at the end of our journey for now, but we have accomplished a lot.
- We added the necessary dependencies to use Http in our application.
- We refactored HeroService to load heroes from an api.
- We extended HeroService to support post, put and delete calls.
- We updated our components to allow adding, editing and deleting of heroes.
- We configured an in-memory web api.
Below is a summary of the files we changed.
+makeTabs(
`toh-6/ts/app/app.component.ts,
toh-6/ts/app/heroes.component.ts,
toh-6/ts/app/heroes.component.html,
toh-6/ts/app/hero-detail.component.ts,
toh-6/ts/app/hero-detail.component.html,
toh-6/ts/app/hero.service.ts`,
null,
`app.comp...ts,
heroes.comp...ts,
heroes.comp...html,
hero-detail.comp...ts,
hero-detail.comp...html,
hero.service.ts`
)

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB