Skip to content

Commit 7d67027

Browse files
committed
docs(toh-6/dart): getHero makes HTTP get-by-id
Dart follow-up to angular#2906
1 parent bc416b8 commit 7d67027

File tree

4 files changed

+51
-21
lines changed

4 files changed

+51
-21
lines changed

public/docs/_examples/toh-6/dart/lib/hero_service.dart

+13-5
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ class HeroService {
1515
static final _headers = {'Content-Type': 'application/json'};
1616
// #enddocregion update
1717
// #docregion getHeroes
18-
static const _heroesUrl = 'app/heroes'; // URL to web API
18+
static const _heroesUrl = 'api/heroes'; // URL to web API
1919

2020
final Client _http;
2121

@@ -46,8 +46,16 @@ class HeroService {
4646
}
4747
// #enddocregion handleError, getHeroes
4848

49-
Future<Hero> getHero(int id) async =>
50-
(await getHeroes()).firstWhere((hero) => hero.id == id);
49+
// #docregion getHero
50+
Future<Hero> getHero(int id) async {
51+
try {
52+
final response = await _http.get('$_heroesUrl/$id');
53+
return new Hero.fromJson(_extractData(response));
54+
} catch (e) {
55+
throw _handleError(e);
56+
}
57+
}
58+
// #enddocregion getHero
5159

5260
// #docregion create
5361
Future<Hero> create(String name) async {
@@ -64,7 +72,7 @@ class HeroService {
6472

6573
Future<Hero> update(Hero hero) async {
6674
try {
67-
var url = '$_heroesUrl/${hero.id}';
75+
final url = '$_heroesUrl/${hero.id}';
6876
final response =
6977
await _http.put(url, headers: _headers, body: JSON.encode(hero));
7078
return new Hero.fromJson(_extractData(response));
@@ -77,7 +85,7 @@ class HeroService {
7785
// #docregion delete
7886
Future<Null> delete(int id) async {
7987
try {
80-
var url = '$_heroesUrl/$id';
88+
final url = '$_heroesUrl/$id';
8189
await _http.delete(url, headers: _headers);
8290
} catch (e) {
8391
throw _handleError(e);

public/docs/_examples/toh-6/dart/lib/in_memory_data_service.dart

+8-3
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,14 @@ class InMemoryDataService extends MockClient {
3131
var data;
3232
switch (request.method) {
3333
case 'GET':
34-
String prefix = request.url.queryParameters['name'] ?? '';
35-
final regExp = new RegExp(prefix, caseSensitive: false);
36-
data = _heroesDb.where((hero) => hero.name.contains(regExp)).toList();
34+
final id = int.parse(request.url.pathSegments.last, onError: (_) => null);
35+
if (id != null) {
36+
data = _heroesDb.firstWhere((hero) => hero.id == id); // throws if no match
37+
} else {
38+
String prefix = request.url.queryParameters['name'] ?? '';
39+
final regExp = new RegExp(prefix, caseSensitive: false);
40+
data = _heroesDb.where((hero) => hero.name.contains(regExp)).toList();
41+
}
3742
break;
3843
// #enddocregion init-disabled
3944
case 'POST':

public/docs/ts/_cache/tutorial/toh-pt6.jade

+29-12
Original file line numberDiff line numberDiff line change
@@ -212,12 +212,32 @@ block get-heroes-details
212212
We've also decided to return a user friendly form of the error to
213213
the caller in a !{rejected_promise} so that the caller can display a proper error message to the user.
214214

215-
### Unchanged `getHeroes` API
215+
### Get hero by id
216+
The `HeroDetailComponent` asks the `HeroService` to fetch a single hero to edit.
217+
218+
The `HeroService` currently fetches all heroes and then finds the desired hero
219+
by filtering for the one with the matching `id`.
220+
That's fine in a simulation. It's wasteful to ask a real server for _all_ heroes when we only want one.
221+
Most web APIs support a _get-by-id_ request in the form `api/hero/:id` (e.g., `api/hero/11`).
216222

217-
Although we made significant *internal* changes to `getHeroes()`, the public signature did not change.
218-
We still return a !{_Promise}. We won't have to update any of the components that call `getHeroes()`.
223+
Update the `HeroService.getHero` method to make a _get-by-id_ request,
224+
applying what we just learned to write `getHeroes`:
225+
+makeExcerpt('app/hero.service.ts', 'getHero', '')
226+
:marked
227+
It's almost the same as `getHeroes`.
228+
The URL identifies _which_ hero the server should update by encoding the hero id into the URL
229+
to match the `api/hero/:id` pattern.
230+
231+
We also adjust to the fact that the `data` in the response is a single hero object rather than !{_an} !{_array}.
232+
233+
### Unchanged _getHeroes_ API
234+
235+
Although we made significant *internal* changes to `getHeroes()` and `getHero()`,
236+
the public signatures did not change.
237+
We still return a !{_Promise} from both methods.
238+
We won't have to update any of the components that call them.
219239

220-
Our stakeholders are thrilled with the added flexibility from the API integration.
240+
Our stakeholders are thrilled with the web API integration so far.
221241
Now they want the ability to create and delete heroes.
222242

223243
Let's see first what happens when we try to update a hero's details.
@@ -230,15 +250,12 @@ block get-heroes-details
230250
it. As we type, the hero name is updated in the view heading.
231251
But when we hit the `Back` button, the changes are lost!
232252

233-
.l-sub-section
234-
:marked
235-
Updates weren't lost before, what's happening?
236-
When the app used a list of mock heroes, changes were made directly to the
237-
hero objects in the single, app-wide shared list. Now that we are fetching data
238-
from a server, if we want changes to persist, we'll need to write them back to
239-
the server.
253+
Updates weren't lost before. What changed?
254+
When the app used a list of mock heroes, updates were applied directly to the
255+
hero objects within the single, app-wide, shared list. Now that we are fetching data
256+
from a server, if we want changes to persist, we'll need to write them back to
257+
the server.
240258

241-
:marked
242259
### Save hero details
243260

244261
Let's ensure that edits to a hero's name aren't lost. Start by adding,

public/docs/ts/latest/tutorial/toh-pt6.jade

+1-1
Original file line numberDiff line numberDiff line change
@@ -228,7 +228,7 @@ block get-heroes-details
228228
The URL identifies _which_ hero the server should update by encoding the hero id into the URL
229229
to match the `api/hero/:id` pattern.
230230

231-
We also adjust to the fact that the `data` in the response is a single hero object rather than array.
231+
We also adjust to the fact that the `data` in the response is a single hero object rather than !{_an} !{_array}.
232232

233233
### Unchanged _getHeroes_ API
234234

0 commit comments

Comments
 (0)