Skip to content
This repository was archived by the owner on Dec 4, 2017. It is now read-only.

Commit 5940799

Browse files
committed
docs(http): remove status 200 guard and add RxJS operators individually
1 parent f5a9edc commit 5940799

12 files changed

+54
-61
lines changed

public/docs/_examples/server-communication/dart/lib/toh/hero_service.dart

-3
Original file line numberDiff line numberDiff line change
@@ -47,9 +47,6 @@ class HeroService {
4747

4848
// #docregion extract-data
4949
dynamic _extractData(Response res) {
50-
if (res.statusCode < 200 || res.statusCode >= 300) {
51-
throw new Exception('Response status: ${res.statusCode}');
52-
}
5350
var body = JSON.decode(res.body);
5451
// TODO: once fixed, https://github.com/adaojunior/http-in-memory-web-api/issues/1
5552
// Drop the `?? body` term
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
// #docregion
2+
// import 'rxjs/Rx'; // adds ALL RxJS operators to Observable
3+
4+
// Just the Observable operators we need for THIS app.
5+
import 'rxjs/add/operator/catch';
6+
import 'rxjs/add/operator/debounceTime';
7+
import 'rxjs/add/operator/distinctUntilChanged';
8+
import 'rxjs/add/operator/map';
9+
import 'rxjs/add/operator/switchMap';

public/docs/_examples/server-communication/ts/app/hero-data.ts

+4-4
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,10 @@
22
export class HeroData {
33
createDb() {
44
let heroes = [
5-
{ "id": "1", "name": "Windstorm" },
6-
{ "id": "2", "name": "Bombasto" },
7-
{ "id": "3", "name": "Magneta" },
8-
{ "id": "4", "name": "Tornado" }
5+
{ id: '1', name: 'Windstorm' },
6+
{ id: '2', name: 'Bombasto' },
7+
{ id: '3', name: 'Magneta' },
8+
{ id: '4', name: 'Tornado' }
99
];
1010
return {heroes};
1111
}

public/docs/_examples/server-communication/ts/app/main.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@ import { HTTP_PROVIDERS } from '@angular/http';
66
// #enddocregion http-providers
77

88
// #docregion import-rxjs
9-
// Add all operators to Observable
10-
import 'rxjs/Rx';
9+
// Add the RxJS Observable operators we need in this app.
10+
import './add-rxjs-operators';
1111
// #enddocregion import-rxjs
1212

1313
import { TohComponent } from './toh/toh.component';

public/docs/_examples/server-communication/ts/app/toh/hero-list.component.1.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ export class HeroListComponent implements OnInit {
2828
}
2929

3030
addHero (name: string) {
31-
if (!name) {return;}
31+
if (!name) { return; }
3232
this.heroService.addHero(name)
3333
.then(
3434
hero => this.heroes.push(hero),

public/docs/_examples/server-communication/ts/app/toh/hero-list.component.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ export class HeroListComponent implements OnInit {
3131

3232
// #docregion addHero
3333
addHero (name: string) {
34-
if (!name) {return;}
34+
if (!name) { return; }
3535
this.heroService.addHero(name)
3636
.subscribe(
3737
hero => this.heroes.push(hero),

public/docs/_examples/server-communication/ts/app/toh/hero.service.1.ts

+3-5
Original file line numberDiff line numberDiff line change
@@ -34,16 +34,14 @@ export class HeroService {
3434
}
3535

3636
private extractData(res: Response) {
37-
if (res.status < 200 || res.status >= 300) {
38-
throw new Error('Bad response status: ' + res.status);
39-
}
4037
let body = res.json();
4138
return body.data || { };
4239
}
4340

4441
private handleError (error: any) {
45-
// In a real world app, we might send the error to remote logging infrastructure
46-
let errMsg = error.message || 'Server error';
42+
// In a real world app, we might use a remote logging infrastructure
43+
// We'd also dig deeper into the error to get a better message
44+
let errMsg = error.message || error.statusText || 'Server error';
4745
console.error(errMsg); // log to console instead
4846
return Promise.reject(errMsg);
4947
}

public/docs/_examples/server-communication/ts/app/toh/hero.service.ts

+3-5
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ export class HeroService {
2929
// #enddocregion error-handling, http-get, v1
3030

3131
// #docregion addhero, addhero-sig
32-
addHero (name: string): Observable<Hero> {
32+
addHero (name: string): Observable<Hero> {
3333
// #enddocregion addhero-sig
3434
let body = JSON.stringify({ name });
3535
let headers = new Headers({ 'Content-Type': 'application/json' });
@@ -43,9 +43,6 @@ export class HeroService {
4343

4444
// #docregion v1, extract-data
4545
private extractData(res: Response) {
46-
if (res.status < 200 || res.status >= 300) {
47-
throw new Error('Response status: ' + res.status);
48-
}
4946
let body = res.json();
5047
return body.data || { };
5148
}
@@ -54,7 +51,8 @@ export class HeroService {
5451
// #docregion error-handling
5552
private handleError (error: any) {
5653
// In a real world app, we might use a remote logging infrastructure
57-
let errMsg = error.message || 'Server error';
54+
// We'd also dig deeper into the error to get a better message
55+
let errMsg = error.message || error.statusText || 'Server error';
5856
console.error(errMsg); // log to console instead
5957
return Observable.throw(errMsg);
6058
}

public/docs/_examples/server-communication/ts/app/wiki/wiki-smart.component.ts

+5-4
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
/* tslint:disable:member-ordering */
12
// #docregion
23
import { Component } from '@angular/core';
34
import { JSONP_PROVIDERS } from '@angular/http';
@@ -20,7 +21,7 @@ import { WikipediaService } from './wikipedia.service';
2021
<li *ngFor="let item of items | async">{{item}}</li>
2122
</ul>
2223
`,
23-
providers:[JSONP_PROVIDERS, WikipediaService]
24+
providers: [JSONP_PROVIDERS, WikipediaService]
2425
})
2526
export class WikiSmartComponent {
2627

@@ -29,13 +30,13 @@ export class WikiSmartComponent {
2930
// #docregion subject
3031
private searchTermStream = new Subject<string>();
3132

32-
search(term:string) { this.searchTermStream.next(term); }
33+
search(term: string) { this.searchTermStream.next(term); }
3334
// #enddocregion subject
3435

3536
// #docregion observable-operators
36-
items:Observable<string[]> = this.searchTermStream
37+
items: Observable<string[]> = this.searchTermStream
3738
.debounceTime(300)
3839
.distinctUntilChanged()
39-
.switchMap((term:string) => this.wikipediaService.search(term));
40+
.switchMap((term: string) => this.wikipediaService.search(term));
4041
// #enddocregion observable-operators
4142
}

public/docs/_examples/server-communication/ts/app/wiki/wiki.component.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ import { WikipediaService } from './wikipedia.service';
1717
<li *ngFor="let item of items | async">{{item}}</li>
1818
</ul>
1919
`,
20-
providers:[JSONP_PROVIDERS, WikipediaService]
20+
providers: [JSONP_PROVIDERS, WikipediaService]
2121
})
2222
export class WikiComponent {
2323

public/docs/_examples/server-communication/ts/app/wiki/wikipedia.service.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ export class WikipediaService {
1111
let wikiUrl = 'http://en.wikipedia.org/w/api.php';
1212

1313
// #docregion search-parameters
14-
var params = new URLSearchParams();
14+
let params = new URLSearchParams();
1515
params.set('search', term); // the user's search value
1616
params.set('action', 'opensearch');
1717
params.set('format', 'json');

public/docs/ts/latest/guide/server-communication.jade

+24-34
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ figure.image-display
6060
:marked
6161
Here is the `TohComponent` shell:
6262
+makeExample('server-communication/ts/app/toh/toh.component.ts', '', 'app/toh/toh.component.ts')
63+
6364
block http-providers
6465
:marked
6566
As usual, we import the symbols we need. The newcomer is `HTTP_PROVIDERS`,
@@ -191,18 +192,26 @@ block rxjs
191192
We should include only those features that we actually need.
192193

193194
Accordingly, Angular exposes a stripped down version of `Observable` in the `rxjs/Observable` module,
194-
a version that lacks almost all operators including the ones we'd like to use here
195+
a version that lacks most of the operators including some we'd like to use here
195196
such as the `map` method we called above in `getHeroes`.
196197

197198
It's up to us to add the operators we need.
198-
We could add each operator, one-by-one, until we had a custom *Observable* implementation tuned
199-
precisely to our requirements.
200-
201-
That would be a distraction today. We're learning HTTP, not counting bytes.
202-
So we'll make it easy on ourselves and enrich *Observable* with the full set of operators.
203-
It only takes one `import` statement.
204-
It's best to add that statement early when we're bootstrapping the application.
205-
:
199+
200+
We could add _every_ RxJS operators with a single import statement.
201+
While that is the easiest thing to do, we'd pay a penalty in extended launch time and application size
202+
because the full library is so big. We only use a few operators in our app.
203+
204+
Instead, we'll import each operator, one-by-one, until we have a custom *Observable* implementation tuned
205+
precisely to our requirements. We'll put the `import` statements in one `app/add-rxjs-operators.ts` file.
206+
+makeExample('server-communication/ts/app/add-rxjs-operators.ts', null, 'app/add-rxjs-operators.ts')(format=".")
207+
:marked
208+
If we forget an operator, the compiler will warn that it's missing and we'll update this file.
209+
.l-sub-section
210+
:marked
211+
We don't need _all_ of these particular operators in the `HeroService` &mdash; just `map` and `catch`.
212+
We'll need the others later, in a *Wiki* example [below](#more-observables).
213+
:marked
214+
Finally, we import `add-rxjs-operator`_itself_ in our `main.ts`:
206215
+makeExample('server-communication/ts/app/main.ts', 'import-rxjs', 'app/main.ts (import rxjs)')(format=".")
207216

208217
a#extract-data
@@ -212,31 +221,8 @@ a#extract-data
212221
+makeExample('server-communication/ts/app/toh/hero.service.ts', 'extract-data', 'app/toh/hero.service.ts (excerpt)')(format=".")
213222
:marked
214223
The `response` object does not hold our data in a form we can use directly.
215-
To make it useful in our application we must
216-
* check the response status,
217-
* parse the response data into a JSON object
224+
To make it useful in our application we must parse the response data into a JSON object
218225

219-
+ifDocsFor('ts')
220-
.alert.is-important
221-
:marked
222-
*Beta alert*: error status interception and parsing may be absorbed within `http` when Angular is released.
223-
224-
:marked
225-
#### Non-success status codes
226-
A status code outside the 200-299 range denotes an error from the _application point of view_
227-
but it is not an error from the _HTTP point of view_.
228-
For example, a `404 - Not Found` is a response like any other.
229-
The request went out; a response came back; here it is, thank you very much.
230-
We'd have an exception only if `#{_priv}http` failed to operate (e.g., it errored internally).
231-
232-
block non-success-status-codes
233-
:marked
234-
Because a status code outside the 200-299 range _is an error_ from the application point of view,
235-
we intercept it and throw, moving the observable chain to the error path.
236-
237-
The `catch` operator that is next in the `getHeroes` observable chain will handle our thrown error.
238-
239-
:marked
240226
#### Parse to JSON
241227
block parse-json
242228
:marked
@@ -597,7 +583,7 @@ block wikipedia-jsonp+
597583
+makeExample('server-communication/ts/app/wiki/wiki-smart.component.ts', 'observable-operators')(format='.')
598584
:marked
599585
We wait for the user to stop typing for at least 300 milliseconds
600-
([debounce](https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/debounce.md)).
586+
([debounceTime](https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/debounce.md)).
601587
Only changed search values make it through to the service
602588
([distinctUntilChanged](https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/distinctuntilchanged.md)).
603589

@@ -611,6 +597,10 @@ block wikipedia-jsonp+
611597
and delivers to subscribers only the most recent search results.
612598

613599
The displayed list of search results stays in sync with the user's sequence of search terms.
600+
.l-sub-section
601+
:marked
602+
We added the `debounceTime`, `distinctUntilChanged`, and `switchMap` operators to the RxJS `Observable` class
603+
in `add-rxjs-operators` as [described above](#rxjs)
614604

615605
a#in-mem-web-api
616606
.l-main-section

0 commit comments

Comments
 (0)