We convert our service and components to use Angular's HTTP service
Our stakeholders appreciate our progress.
Now they want to get the hero data from a server, let users add, edit, and delete heroes,
and save these changes back to the server.
In this chapter we teach our application to make the corresponding HTTP calls to a remote server's web API.
Run the for this part.
Where We Left Off
In the previous chapter, we learned to navigate between the dashboard and the fixed heroes list, editing a selected hero along the way.
That's our starting point for this chapter.
Keep the app compiling and running
Open a terminal/console window.
Start the Dart compiler, watch for changes, and start our server by entering the command:
pub serve
The application runs and updates automatically as we continue to build the Tour of Heroes.
Providing HTTP Services
We'll be using the Dart http package's
BrowserClient class to communicate with a server.
Pubspec updates
Update package dependencies by adding the
stream_transformers and Dart http packages.
We also need to add a resolved_identifiers entry, to inform the angular2
transformer that we'll be using BrowserClient. (For an explanation of why
this extra configuration is needed, see the HTTP client chapter.) We'll
also need to use Client from http, so let's add that now as well.
Update pubspec.yaml to look like this (additions are highlighted):
Before our app can use BrowserClient, we have to register it as a service provider.
We should be able to access BrowserClient services from anywhere in the application.
So we register it in the bootstrap call where we
launch the application and its root AppComponent.
Notice that we supply BrowserClient in a list, as the second parameter to
the bootstrap method. This has the same effect as the providers list in
@Component annotation.
Simulating the web API
We recommend registering application-wide services in the root
AppComponentproviders. 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 mock 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 web/main.dart that performs this trick:
web/main.dart (v2)
import 'package:angular2/core.dart';
import 'package:angular2/platform/browser.dart';
import 'package:angular_tour_of_heroes/app_component.dart';
import 'package:angular_tour_of_heroes/in_memory_data_service.dart';
import 'package:http/http.dart';
void main() {
bootstrap(AppComponent,
[provide(Client, useClass: InMemoryDataService)]
// Using a real back end? Import browser_client.dart and change the above to
// [provide(Client, useFactory: () => new BrowserClient(), deps: [])]
);
}
We want to replace BrowserClient, the service that talks to the remote server,
with the in-memory web API service.
Our in-memory web API service, shown below, is implemented using the
http library MockClient class.
All http client implementations share a common Client interface, so
we'll have our app use the Client type so that we can freely switch between
implementations.
lib/in_memory_data_service.dart
import 'dart:async';
import 'dart:convert';
import 'dart:math';
import 'package:angular2/core.dart';
import 'package:http/http.dart';
import 'package:http/testing.dart';
import 'hero.dart';
@Injectable()
class InMemoryDataService extends MockClient {
static final _initialHeroes = [
{'id': 11, 'name': 'Mr. Nice'},
{'id': 12, 'name': 'Narco'},
{'id': 13, 'name': 'Bombasto'},
{'id': 14, 'name': 'Celeritas'},
{'id': 15, 'name': 'Magneta'},
{'id': 16, 'name': 'RubberMan'},
{'id': 17, 'name': 'Dynama2'},
{'id': 18, 'name': 'Dr IQ'},
{'id': 19, 'name': 'Magma'},
{'id': 20, 'name': 'Tornado'}
];
static final List<Hero> _heroesDb =
_initialHeroes.map((json) => new Hero.fromJson(json)).toList();
static int _nextId = _heroesDb.map((hero) => hero.id).reduce(max) + 1;
static Future<Response> _handler(Request request) async {
var data;
switch (request.method) {
case 'GET':
String prefix = request.url.queryParameters['name'] ?? '';
final regExp = new RegExp(prefix, caseSensitive: false);
data = _heroesDb.where((hero) => hero.name.contains(regExp)).toList();
break;
case 'POST':
var name = JSON.decode(request.body)['name'];
var newHero = new Hero(_nextId++, name);
_heroesDb.add(newHero);
data = newHero;
break;
case 'PUT':
var heroChanges = new Hero.fromJson(JSON.decode(request.body));
var targetHero = _heroesDb.firstWhere((h) => h.id == heroChanges.id);
targetHero.name = heroChanges.name;
data = targetHero;
break;
case 'DELETE':
var id = int.parse(request.url.pathSegments.last);
_heroesDb.removeWhere((hero) => hero.id == id);
// No data, so leave it as null.
break;
default:
throw 'Unimplemented HTTP method ${request.method}';
}
return new Response(JSON.encode({'data': data}), 200,
headers: {'content-type': 'application/json'});
}
InMemoryDataService() : super(_handler);
}
This file replaces the mock_heroes.dart which is now safe to delete.
As is common for web API services, our mock in-memory service will be
encoding and decoding heroes in JSON format, so we enhance the Hero
class with these capabilities:
lib/hero.dart
class Hero {
final int id;
String name;
Hero(this.id, this.name);
factory Hero.fromJson(Map<String, dynamic> hero) =>
new Hero(_toInt(hero['id']), hero['name']);
Map toJson() => {'id': id, 'name': name};
}
int _toInt(id) => id is int ? id : int.parse(id);
We returned a Future 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 HTTP.
lib/hero_service.dart (updated getHeroes and new class members)
static const _heroesUrl = 'app/heroes'; // URL to web API
final Client _http;
HeroService(this._http);
Future<List<Hero>> getHeroes() async {
try {
final response = await _http.get(_heroesUrl);
final heroes = _extractData(response)
.map((value) => new Hero.fromJson(value))
.toList();
return heroes;
} catch (e) {
throw _handleError(e);
}
}
dynamic _extractData(Response resp) => JSON.decode(resp.body)['data'];
Exception _handleError(dynamic e) {
print(e); // for demo purposes only
return new Exception('Server error; cause: $e');
}
Refresh the browser, and the hero data should be successfully loaded from the
mock server.
HTTP Future
We're still returning a Future but we're creating it differently.
To get the list of heroes, we first make an asynchronous call to
http.get(). Then we use the _extractData helper method to decode the
response body.
That response JSON has a single data property.
The data property holds the list of heroes that the caller really wants.
So we grab that list and return it as the resolved Future value.
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.
The caller is unaware of these machinations. It receives a Future of heroes just as it did before.
It has no idea that we fetched the heroes from the (mock) server.
It knows nothing of the twists and turns required to convert the HTTP response into heroes.
Such is the beauty and purpose of delegating data access to a service like this HeroService.
Error Handling
At the end of getHeroes() we catch server failures and pass them to an error handler:
} catch (e) {
throw _handleError(e);
}
This is a critical step!
We must anticipate HTTP failures as they happen frequently for reasons beyond our control.
Exception _handleError(dynamic e) {
print(e); // for demo purposes only
return new Exception('Server error; cause: $e');
}
In this demo service we log the error to the console; we would do better in real life.
We've also decided to return a user friendly form of the error to
the caller in a propagated exception so that the caller can display a proper error message to the user.
Unchanged getHeroes API
Although we made significant internal changes to getHeroes(), the public signature did not change.
We still return a Future. We won't have to update any of the components that call getHeroes().
Our stakeholders are thrilled with the added flexibility from the API integration.
Now they want the ability to create and delete heroes.
Let's see first what happens when we try to update a hero's details.
Update hero details
We can edit a hero's name already in the hero detail view. Go ahead and try
it. As we type, the hero name is updated in the view heading.
But when we hit the Back button, the changes are lost!
Updates weren't lost before, what's happening?
When the app used a list of mock heroes, changes were made directly to the
hero objects in the single, app-wide shared list. Now that we are fetching data
from a server, if we want changes to persist, we'll need to write them back to
the server.
Save hero details
Let's ensure that edits to a hero's name aren't lost. Start by adding,
to the end of the hero detail template, a save button with a click event
binding that invokes a new component method named save:
lib/hero_detail_component.html (save)
<button (click)="save()">Save</button>
The save method persists hero name changes using the hero service
update method and then navigates back to the previous view:
The overall structure of the update method is similar to that of
getHeroes, although we'll use an HTTP put to persist changes
server-side:
lib/hero_service.dart (update)
static final _headers = {'Content-Type': 'application/json'};
Future<Hero> update(Hero hero) async {
try {
var url = '$_heroesUrl/${hero.id}';
final response =
await _http.put(url, headers: _headers, body: JSON.encode(hero));
return new Hero.fromJson(_extractData(response));
} catch (e) {
throw _handleError(e);
}
}
We identify which hero the server should update by encoding the hero id in
the URL. The put body is the JSON string encoding of the hero, obtained by
calling JSON.encode. We identify the body content type
(application/json) in the request header.
Refresh the browser and give it a try. Changes to hero names should now persist.
Add a hero
To add a new hero we need to know the hero's name. Let's use an input
element for that, paired with an add button.
Insert the following into the heroes component HTML, first thing after
the heading:
In addition to calling the component's delete method, the delete button
click handling code stops the propagation of the click event — we
don't want the <li> click handler to be triggered because that would
select the hero that we are going to delete!
The logic of the delete handler is a bit trickier:
Of course, we delegate hero deletion to the hero service, but the component
is still responsible for updating the display: it removes the deleted hero
from the list and resets the selected hero if necessary.
We want our delete button to be placed at the far right of the hero entry.
This extra CSS accomplishes that:
Refresh the browser and try the new delete functionality.
Streams
Recall that HeroService.getHeroes() awaits for an http.get()
response and yields a FutureList<Hero>, which is fine when we are only
interested in a single result.
But requests aren't always "one and done". We may start one request,
then cancel it, and make a different request before the server has responded to the first request.
Such a request-cancel-new-request sequence is difficult to implement with Futures.
It's easy with Streams as we'll see.
Search-by-name
We're going to add a hero search feature to the Tour of Heroes.
As the user types a name into a search box, we'll make repeated HTTP requests for heroes filtered by that name.
We start by creating HeroSearchService that sends search queries to our server's web api.
lib/hero_search_service.dart
import 'dart:async';
import 'dart:convert';
import 'package:angular2/core.dart';
import 'package:http/http.dart';
import 'hero.dart';
@Injectable()
class HeroSearchService {
final Client _http;
HeroSearchService(this._http);
Future<List<Hero>> search(String term) async {
try {
final response = await _http.get('app/heroes/?name=$term');
return _extractData(response)
.map((json) => new Hero.fromJson(json))
.toList();
} catch (e) {
throw _handleError(e);
}
}
dynamic _extractData(Response resp) => JSON.decode(resp.body)['data'];
Exception _handleError(dynamic e) {
print(e); // for demo purposes only
return new Exception('Server error; cause: $e');
}
}
The _http.get() call in HeroSearchService is similar to the one
in the HeroService, although the URL now has a query string.
Another notable difference: we no longer call toPromise,
we simply return the observable instead.
HeroSearchComponent
Let's create a new HeroSearchComponent that calls this new HeroSearchService.
The component template is simple — just a text box and a list of matching search results.
As the user types in the search box, a keyup event binding calls the component's search method with the new search box value.
The *ngFor repeats hero objects from the component's heroes property. No surprise there.
But, as we'll soon see, the heroes property is now a Stream of hero lists, rather than just a hero list.
The *ngFor can't do anything with a Stream until we flow it through the async pipe (AsyncPipe).
The async pipe subscribes to the Stream and produces the list of heroes to *ngFor.
Time to create the HeroSearchComponent class and metadata.
lib/hero_search_component.dart
import 'dart:async';
import 'package:angular2/core.dart';
import 'package:angular2/router.dart';
import 'package:stream_transformers/stream_transformers.dart';
import 'hero_search_service.dart';
import 'hero.dart';
@Component(
selector: 'hero-search',
templateUrl: 'hero_search_component.html',
styleUrls: const ['hero_search_component.css'],
providers: const [HeroSearchService])
class HeroSearchComponent implements OnInit {
HeroSearchService _heroSearchService;
Router _router;
Stream<List<Hero>> heroes;
StreamController<String> _searchTerms =
new StreamController<String>.broadcast();
HeroSearchComponent(this._heroSearchService, this._router) {}
// Push a search term into the stream.
void search(String term) => _searchTerms.add(term);
Future<Null> ngOnInit() async {
heroes = _searchTerms.stream
.transform(new Debounce(new Duration(milliseconds: 300)))
.distinct()
.transform(new FlatMapLatest((term) => term.isEmpty
? new Stream<List<Hero>>.fromIterable([<Hero>[]])
: _heroSearchService.search(term).asStream()))
.handleError((e) {
print(e); // for demo purposes only
});
}
void gotoDetail(Hero hero) {
var link = [
'HeroDetail',
{'id': hero.id.toString()}
];
_router.navigate(link);
}
}
Search terms
Let's focus on the _searchTerms:
StreamController<String> _searchTerms =
new StreamController<String>.broadcast();
// Push a search term into the stream.
void search(String term) => _searchTerms.add(term);
A StreamController, as its name implies, is a controller for a Stream that allows us to
manipulate the underlying stream by adding data to it, for example.
In our sample, the underlying stream of strings (_searchTerms.stream) represents the hero
name search patterns entered by the user. Each call to search puts a new string into
the stream by calling add over the controller.
Initialize the heroes property (ngOnInit)
A Subject is also an Observable.
We're going to turn the stream
of search terms into a stream of Hero lists and assign the result to the heroes property.
If we passed every user keystroke directly to the HeroSearchService, we'd unleash a storm of HTTP requests.
Bad idea. We don't want to tax our server resources and burn through our cellular network data plan.
Fortunately, there are stream transformers that will help us reduce the request flow.
We'll make fewer calls to the HeroSearchService and still get timely results. Here's how:
transform(new Debounce(... 300))) waits until the flow of search terms pauses for 300
milliseconds before passing along the latest string. We'll never make requests more frequently
than 300ms.
distinct() ensures that we only send a request if a search term has changed.
There's no point in repeating a request for the same search term.
transform(new FlatMapLatest(...)) applies a map-like transformer that (1) calls our search
service for each search term that makes it through the debounce and distinct gauntlet and (2)
returns only the most recent search service result, discarding any previous results.
handleError() handles errors. Our simple example prints the error to the console; a real
life application should do better.
Add the search component to the dashboard
We add the hero search HTML element to the bottom of the DashboardComponent template.