2016-05-13 16:32:54 -04:00
block includes
include ../_util-fns
2016-05-18 00:25:41 -04:00
2015-12-01 06:15:14 -05:00
:marked
2016-02-04 01:28:39 -05:00
[HTTP](https://tools.ietf.org/html/rfc2616) is the primary protocol for browser/server communication.
.l-sub-section
:marked
The [`WebSocket`](https://tools.ietf.org/html/rfc6455) protocol is another important communication technology;
2016-10-20 02:17:50 -04:00
it isn't covered in this page.
2016-02-04 01:28:39 -05:00
:marked
2016-10-20 02:17:50 -04:00
Modern browsers support two HTTP-based APIs:
[XMLHttpRequest (XHR)](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) and
2016-02-04 01:28:39 -05:00
[JSONP](https://en.wikipedia.org/wiki/JSONP). A few browsers also support
2016-10-20 02:17:50 -04:00
[Fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API).
2017-03-30 19:13:42 -04:00
The Angular HTTP library simplifies application programming with the **XHR** and **JSONP** APIs.
2017-03-09 15:54:14 -05:00
# Contents
2017-03-30 17:41:23 -04:00
2017-03-09 15:54:14 -05:00
* [Demos](#demos)
* [Providing HTTP Services](#http-providers)
* [The Tour of Heroes *HTTP* client demo](#http-client)
- [The `HeroListComponent` class](#HeroListComponent)
* [Fetch data with `http.get()`](#fetch-data)
2017-03-30 19:13:42 -04:00
<li>[RxJS library](#rxjs-library)
2017-03-09 15:54:14 -05:00
<ul>
<li> [Enable RxJS operators](#enable-rxjs-operators)</li>
2016-07-03 20:11:17 -04:00
</ul>
2017-03-09 15:54:14 -05:00
</li>
* [Process the response object](#extract-data)
- [Parse to `JSON`](#parse-to-json)
- [Do not return the response object](#no-return-response-object)
- [Always handle errors](#error-handling)
- [`HeroListComponent` error handling](#hero-list-component)
* [Send data to the server](#update)
- [Headers](#headers)
- [JSON results](#json-results)
2017-03-30 19:13:42 -04:00
<ul><li> [Fall back to promises](#promises)</ul>
2017-03-09 15:54:14 -05:00
* [Cross-Origin Requests: Wikipedia example](#cors)
2017-03-30 19:13:42 -04:00
<ul>
2017-03-09 15:54:14 -05:00
<li> [Search Wikipedia](#search-wikipedia)</li>
<li> [Search parameters](#search-parameters)</li>
<li> [The WikiComponent](#wikicomponent)</li>
</ul>
* [A wasteful app](#wasteful-app)
2017-03-30 19:13:42 -04:00
<li> [More fun with Observables](#more-observables)
2017-03-09 15:54:14 -05:00
<ul>
<li> [Create a stream of search terms](#create-stream)</li>
<li> [Listen for search terms](#listen-for-search-terms)</li>
</ul>
</li>
* [Guarding against Cross-Site Request Forgery](#xsrf)
* [Override default request headers (and other request options)](#override-default-request-options)
* [Appendix: Tour of Heroes _in-memory web api_](#in-mem-web-api)
2016-10-20 02:17:50 -04:00
A <live-example>live example</live-example> illustrates these topics.
2016-07-03 20:11:17 -04:00
2017-03-09 15:54:14 -05:00
a#demos
2016-05-18 00:25:41 -04:00
.l-main-section
2016-07-03 20:11:17 -04:00
:marked
# Demos
2016-10-20 02:17:50 -04:00
This page describes server communication with the help of the following demos:
2016-07-03 20:11:17 -04:00
block demos-list
:marked
2016-10-20 02:17:50 -04:00
- [The Tour of Heroes *HTTP* client demo](#http-client).
2017-03-30 19:13:42 -04:00
- [Fall back to Promises](#promises).
2016-10-24 05:57:19 -04:00
- [Cross-Origin Requests: Wikipedia example](#cors).
2017-03-09 15:54:14 -05:00
- [More fun with Observables](#more-observables).
2016-07-03 20:11:17 -04:00
2016-05-18 00:25:41 -04:00
:marked
2016-10-20 02:17:50 -04:00
The root `AppComponent` orchestrates these demos:
2017-02-02 13:38:17 -05:00
+makeExample('server-communication/ts/src/app/app.component.ts', null, 'src/app/app.component.ts')
2016-05-18 00:25:41 -04:00
2016-07-03 20:11:17 -04:00
.l-main-section#http-providers
2016-02-04 01:28:39 -05:00
:marked
2016-10-20 02:17:50 -04:00
# Providing HTTP services
2016-07-03 20:11:17 -04:00
2016-10-20 02:17:50 -04:00
First, configure the application to use server communication facilities.
2017-03-30 19:13:42 -04:00
The Angular <code>Http</code> client communicates with the server using a familiar HTTP request/response protocol.
The `Http` client is one of a family of services in the Angular HTTP library.
2016-07-03 20:11:17 -04:00
2017-03-30 19:13:42 -04:00
.l-sub-section
:marked
When importing from the `@angular/http` module, SystemJS knows how to load services from
the Angular HTTP library
because the `systemjs.config.js` file maps to that module name.
2016-07-03 20:11:17 -04:00
2015-12-01 06:15:14 -05:00
:marked
2017-03-30 19:13:42 -04:00
Before you can use the `Http` client, you need to register it as a service provider with the dependency injection system.
2016-07-03 20:11:17 -04:00
2015-12-01 06:15:14 -05:00
.l-sub-section
:marked
2016-10-20 02:17:50 -04:00
Read about providers in the [Dependency Injection](dependency-injection.html) page.
2016-05-18 00:25:41 -04:00
2016-07-03 20:11:17 -04:00
:marked
2016-10-20 02:17:50 -04:00
Register providers by importing other NgModules to the root NgModule in `app.module.ts`.
2016-07-03 20:11:17 -04:00
2017-02-02 13:38:17 -05:00
+makeExample('server-communication/ts/src/app/app.module.1.ts', null, 'src/app/app.module.ts (v1)')(format='.')
2016-05-17 04:45:52 -04:00
2016-05-13 16:32:54 -04:00
block http-providers
2016-04-13 11:21:32 -04:00
:marked
2016-10-20 02:17:50 -04:00
Begin by importing the necessary members.
2017-03-30 19:13:42 -04:00
The newcomers are the `HttpModule` and the `JsonpModule` from the Angular HTTP library. For more information about imports and related terminology, see the [MDN reference](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import) on the `import` statement.
2016-10-20 02:17:50 -04:00
To add these modules to the application, pass them to the `imports` array in the root `@NgModule`.
2017-03-14 13:48:21 -04:00
.l-sub-section
:marked
The `HttpModule` is necessary for making HTTP calls.
Though the `JsonpModule` isn't necessary for plain HTTP,
there is a JSONP demo later in this page.
Loading its module now saves time.
.l-main-section#http-client
2016-05-18 00:25:41 -04:00
:marked
2016-11-16 13:02:31 -05:00
## The Tour of Heroes HTTP client demo
2016-07-03 20:11:17 -04:00
2016-10-20 02:17:50 -04:00
The first demo is a mini-version of the [tutorial](../tutorial)'s "Tour of Heroes" (ToH) application.
This version gets some heroes from the server, displays them in a list, lets the user add new heroes, and saves them to the server.
2017-03-30 19:13:42 -04:00
The app uses the Angular <code>Http</code> client to communicate via **XMLHttpRequest (XHR)**.
2016-05-18 00:25:41 -04:00
2016-10-20 02:17:50 -04:00
It works like this:
2016-05-18 00:25:41 -04:00
figure.image-display
img(src='/resources/images/devguide/server-communication/http-toh.gif' alt="ToH mini app" width="250")
2015-12-01 06:15:14 -05:00
:marked
2016-05-18 00:25:41 -04:00
This demo has a single component, the `HeroListComponent`. Here's its template:
2017-03-14 13:48:21 -04:00
+makeExample('server-communication/ts/src/app/toh/hero-list.component.html', null, 'src/app/toh/hero-list.component.html')
2015-12-01 06:15:14 -05:00
:marked
2016-10-20 02:17:50 -04:00
It presents the list of heroes with an `ngFor`.
Below the list is an input box and an *Add Hero* button where you can enter the names of new heroes
and add them to the database.
A [template reference variable](template-syntax.html#ref-vars), `newHeroName`, accesses the
2016-04-27 14:28:22 -04:00
value of the input box in the `(click)` event binding.
2017-03-14 13:48:21 -04:00
When the user clicks the button, that value is passed to the component's `addHero` method and then
2016-10-20 02:17:50 -04:00
the event binding clears it to make it ready for a new hero name.
2016-05-13 16:32:54 -04:00
Below the button is an area for an error message.
2016-01-23 13:21:09 -05:00
2016-05-18 00:25:41 -04:00
a#oninit
a#HeroListComponent
2016-01-23 13:21:09 -05:00
:marked
2016-11-16 13:02:31 -05:00
### The *HeroListComponent* class
2016-04-13 11:21:32 -04:00
Here's the component class:
2017-02-02 13:38:17 -05:00
+makeExample('server-communication/ts/src/app/toh/hero-list.component.ts','component', 'src/app/toh/hero-list.component.ts (class)')
2016-04-13 11:21:32 -04:00
:marked
2016-05-18 00:25:41 -04:00
Angular [injects](dependency-injection.html) a `HeroService` into the constructor
and the component calls that service to fetch and save data.
2015-12-01 06:15:14 -05:00
2017-03-30 19:13:42 -04:00
The component **does not talk directly to the Angular <code>Http</code> client**.
2016-10-20 02:17:50 -04:00
The component doesn't know or care how it gets the data.
2016-05-18 00:25:41 -04:00
It delegates to the `HeroService`.
2016-10-20 02:17:50 -04:00
2016-04-13 11:21:32 -04:00
This is a golden rule: **always delegate data access to a supporting service class**.
2016-01-23 13:21:09 -05:00
2016-10-20 02:17:50 -04:00
Although _at runtime_ the component requests heroes immediately after creation,
you **don't** call the service's `get` method in the component's constructor.
Instead, call it inside the `ngOnInit` [lifecycle hook](lifecycle-hooks.html)
and rely on Angular to call `ngOnInit` when it instantiates this component.
2015-12-01 06:15:14 -05:00
.l-sub-section
:marked
2016-10-20 02:17:50 -04:00
This is a *best practice*.
Components are easier to test and debug when their constructors are simple, and all real work
2015-12-01 06:15:14 -05:00
(especially calling a remote server) is handled in a separate method.
2017-03-14 13:48:21 -04:00
block getheroes-and-create
2016-05-13 16:32:54 -04:00
:marked
2017-03-30 19:13:42 -04:00
The service's `getHeroes()` and `create()` methods return an `Observable` of hero data that the Angular <code>Http</code> client fetched from the server.
2016-10-20 02:17:50 -04:00
Think of an `Observable` as a stream of events published by some source.
To listen for events in this stream, ***subscribe*** to the `Observable`.
These subscriptions specify the actions to take when the web request
2016-05-18 00:25:41 -04:00
produces a success event (with the hero data in the event payload) or a fail event (with the error in the payload).
2016-05-13 16:32:54 -04:00
2015-12-01 06:15:14 -05:00
:marked
2016-10-20 02:17:50 -04:00
With a basic understanding of the component, you're ready to look inside the `HeroService`.
2016-05-18 00:25:41 -04:00
a#HeroService
2016-07-03 20:11:17 -04:00
.l-main-section#fetch-data
2016-05-18 00:25:41 -04:00
:marked
2017-03-09 15:54:14 -05:00
## Fetch data with _http.get()_
2016-07-03 20:11:17 -04:00
2016-10-20 02:17:50 -04:00
In many of the previous samples the app faked the interaction with the server by
2015-12-01 06:15:14 -05:00
returning mock heroes in a service like this one:
2017-02-02 13:38:17 -05:00
+makeExample('toh-4/ts/src/app/hero.service.ts', 'just-get-heroes')(format=".")
2015-12-01 06:15:14 -05:00
:marked
2017-03-30 19:13:42 -04:00
You can revise that `HeroService` to get the heroes from the server using the Angular <code>Http</code> client service:
2017-02-02 13:38:17 -05:00
+makeExample('server-communication/ts/src/app/toh/hero.service.ts', 'v1', 'src/app/toh/hero.service.ts (revised)')
2016-05-13 16:32:54 -04:00
2016-05-18 00:25:41 -04:00
:marked
2017-03-30 19:13:42 -04:00
Notice that the Angular <code>Http</code> client service is
2016-05-18 00:25:41 -04:00
[injected](dependency-injection.html) into the `HeroService` constructor.
2017-02-02 13:38:17 -05:00
+makeExample('server-communication/ts/src/app/toh/hero.service.ts', 'ctor')
2015-12-01 06:15:14 -05:00
:marked
2017-03-30 19:13:42 -04:00
Look closely at how to call `http.get`:
2017-02-02 13:38:17 -05:00
+makeExample('server-communication/ts/src/app/toh/hero.service.ts', 'http-get', 'src/app/toh/hero.service.ts (getHeroes)')(format=".")
2015-12-01 06:15:14 -05:00
:marked
2016-10-20 02:17:50 -04:00
You pass the resource URL to `get` and it calls the server which returns heroes.
2016-02-17 12:13:57 -05:00
.l-sub-section
:marked
2016-10-20 02:17:50 -04:00
The server returns heroes once you've set up the [in-memory web api](#in-mem-web-api)
2016-02-17 12:13:57 -05:00
described in the appendix below.
2016-10-20 02:17:50 -04:00
Alternatively, you can temporarily target a JSON file by changing the endpoint URL:
2017-02-02 13:38:17 -05:00
+makeExample('server-communication/ts/src/app/toh/hero.service.ts', 'endpoint-json')(format=".")
2016-02-04 01:28:39 -05:00
2017-03-30 19:13:42 -04:00
:marked
<a id="rxjs"></a>
If you are familiar with asynchronous methods in modern JavaScript, you might expect the `get` method to return a
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" target="_blank" title="Promise">promise</a>.
You'd expect to chain a call to `then()` and extract the heroes.
Instead you're calling a `map()` method.
Clearly this is not a promise.
2016-05-03 10:26:09 -04:00
2017-03-30 19:13:42 -04:00
In fact, the `http.get` method returns an **Observable** of HTTP Responses (`Observable<Response>`) from the RxJS library
and `map()` is one of the RxJS *operators*.
2016-05-13 16:32:54 -04:00
2017-03-30 19:13:42 -04:00
a#rxjs-library
.l-main-section
:marked
## RxJS library
<a href="http://reactivex.io/rxjs" target="_blank" title="RxJS Reactive Extensions">RxJS</a>
is a third party library, endorsed by Angular, that implements the
<a href="https://www.youtube.com/watch?v=VLGCCpOWFFw" target="_blank" title="Video: Rob Wormald on Observables"><b>asynchronous Observable</b></a> pattern.
2016-05-13 16:32:54 -04:00
2017-03-30 19:13:42 -04:00
All of the Developer Guide samples have installed the RxJS npm package
because Observables are used widely in Angular applications.
_This_ app needs it when working with the HTTP client.
But you must take a critical extra step to make RxJS Observables usable:
_you must import the RxJS operators individually_.
2016-10-20 02:17:50 -04:00
2017-03-30 19:13:42 -04:00
### Enable RxJS operators
The RxJS library is large.
Size matters when building a production application and deploying it to mobile devices.
You should include only necessary features.
2016-10-20 02:17:50 -04:00
2017-03-30 19:13:42 -04:00
Each code file should add the operators it needs by importing from an RxJS library.
The `getHeroes()` method needs the `map()` and `catch()` operators so it imports them like this.
+makeExample('server-communication/ts/src/app/toh/hero.service.ts', 'rxjs-imports', 'src/app/app.component.ts (import rxjs)')(format=".")
2016-10-20 02:17:50 -04:00
2016-09-06 13:28:24 -04:00
.l-main-section
2016-05-13 16:32:54 -04:00
a#extract-data
2015-12-01 06:15:14 -05:00
:marked
2016-05-18 00:25:41 -04:00
## Process the response object
2017-03-30 19:13:42 -04:00
Remember that the `getHeroes()` method used an `extractData()` helper method to map the `http.get` response object to heroes:
2017-02-02 13:38:17 -05:00
+makeExample('server-communication/ts/src/app/toh/hero.service.ts', 'extract-data', 'src/app/toh/hero.service.ts (excerpt)')(format=".")
2015-12-01 06:15:14 -05:00
:marked
2016-10-20 02:17:50 -04:00
The `response` object doesn't hold the data in a form the app can use directly.
You must parse the response data into a JSON object.
2016-05-13 16:32:54 -04:00
2017-03-09 15:54:14 -05:00
a#parse-to-json
:marked
2016-10-20 02:17:50 -04:00
### Parse to JSON
2016-05-13 16:32:54 -04:00
block parse-json
2015-12-01 06:15:14 -05:00
:marked
2016-05-13 16:32:54 -04:00
The response data are in JSON string form.
2016-10-20 02:17:50 -04:00
The app must parse that string into JavaScript objects by calling `response.json()`.
2016-05-13 16:32:54 -04:00
.l-sub-section
:marked
2016-10-20 02:17:50 -04:00
This is not Angular's own design.
2016-08-13 07:41:06 -04:00
The Angular HTTP client follows the Fetch specification for the
2016-05-13 16:32:54 -04:00
[response object](https://fetch.spec.whatwg.org/#response-class) returned by the `Fetch` function.
That spec defines a `json()` method that parses the response body into a JavaScript object.
2016-02-17 12:13:57 -05:00
.l-sub-section
:marked
2017-03-30 19:13:42 -04:00
Don't expect the decoded JSON to be the heroes array directly.
2016-10-20 02:17:50 -04:00
This server always wraps JSON results in an object with a `data`
property. You have to unwrap it to get the heroes.
This is conventional web API behavior, driven by
2015-12-23 12:42:57 -05:00
[security concerns](https://www.owasp.org/index.php/OWASP_AJAX_Security_Guidelines#Always_return_JSON_with_an_Object_on_the_outside).
2016-10-20 02:17:50 -04:00
2016-02-17 12:13:57 -05:00
.alert.is-important
:marked
2016-10-20 02:17:50 -04:00
Make no assumptions about the server API.
2016-02-17 12:13:57 -05:00
Not all servers return an object with a `data` property.
2017-03-09 15:54:14 -05:00
a#no-return-response-object
2015-12-01 06:15:14 -05:00
:marked
### Do not return the response object
2016-10-20 02:17:50 -04:00
The `getHeroes()` method _could_ have returned the HTTP response but this wouldn't
2017-03-14 13:48:21 -04:00
follow best practices.
2016-05-13 16:32:54 -04:00
The point of a data service is to hide the server interaction details from consumers.
2016-10-20 02:17:50 -04:00
The component that calls the `HeroService` only wants heroes and is kept separate
from getting them, the code dealing with where they come from, and the response object.
2015-12-01 06:15:14 -05:00
2017-03-30 19:13:42 -04:00
.callout.is-important
header HTTP GET is delayed
:marked
The `http.get` does **not send the request just yet.** This Observable is
[*cold*](https://github.com/Reactive-Extensions/RxJS/blob/master/doc/gettingstarted/creating.md#cold-vs-hot-observables),
which means that the request won't go out until something *subscribes* to the Observable.
That *something* is the [HeroListComponent](#subscribe).
2016-05-13 16:32:54 -04:00
a#error-handling
2016-04-13 11:21:32 -04:00
:marked
2015-12-01 06:15:14 -05:00
### Always handle errors
2016-10-20 02:17:50 -04:00
An important part of dealing with I/O is anticipating errors by preparing to catch them
and do something with them. One way to handle errors is to pass an error message
back to the component for presentation to the user,
but only if it says something that the user can understand and act upon.
2017-03-30 17:41:23 -04:00
2016-10-20 02:17:50 -04:00
This simple app conveys that idea, albeit imperfectly, in the way it handles a `getHeroes` error.
2017-02-02 13:38:17 -05:00
+makeExample('server-communication/ts/src/app/toh/hero.service.ts', 'error-handling', 'src/app/toh/hero.service.ts (excerpt)')(format=".")
2016-01-28 04:22:59 -05:00
2016-05-13 16:32:54 -04:00
block error-handling
:marked
2017-03-09 15:54:14 -05:00
The `catch()` operator passes the error object from `http` to the `handleError()` method.
2017-03-30 17:41:23 -04:00
The `handleError` method transforms the error into a developer-friendly message,
2017-03-09 15:54:14 -05:00
logs it to the console, and returns the message in a new, failed Observable via `Observable.throw`.
2016-05-13 16:32:54 -04:00
a#subscribe
a#hero-list-component
2016-10-20 02:17:50 -04:00
h3 #[b HeroListComponent] error handling
2016-05-13 16:32:54 -04:00
block hlc-error-handling
:marked
2017-03-30 19:13:42 -04:00
Back in the `HeroListComponent`, in `heroService.getHeroes()`,
2016-10-20 02:17:50 -04:00
the `subscribe` function has a second function parameter to handle the error message.
It sets an `errorMessage` variable that's bound conditionally in the `HeroListComponent` template.
2015-12-01 06:15:14 -05:00
2017-02-02 13:38:17 -05:00
+makeExample('server-communication/ts/src/app/toh/hero-list.component.ts', 'getHeroes', 'src/app/toh/hero-list.component.ts (getHeroes)')(format=".")
2016-10-20 02:17:50 -04:00
2016-01-28 04:22:59 -05:00
.l-sub-section
:marked
2016-10-20 02:17:50 -04:00
Want to see it fail? In the `HeroService`, reset the api endpoint to a bad value. Afterward, remember to restore it.
2016-04-13 11:21:32 -04:00
2017-03-14 13:48:21 -04:00
<a id="create"></a>
2016-02-01 19:49:24 -05:00
<a id="update"></a>
<a id="post"></a>
.l-main-section
2015-12-01 06:15:14 -05:00
:marked
2016-02-01 19:49:24 -05:00
## Send data to the server
2015-12-01 06:15:14 -05:00
2016-10-20 02:17:50 -04:00
So far you've seen how to retrieve data from a remote location using an HTTP service.
Now you'll add the ability to create new heroes and save them in the backend.
2017-03-14 13:48:21 -04:00
You'll write a method for the `HeroListComponent` to call, a `create()` method, that takes
2016-10-20 02:17:50 -04:00
just the name of a new hero and returns an `Observable` of `Hero`. It begins like this:
2016-05-13 16:32:54 -04:00
2017-03-14 13:48:21 -04:00
+makeExample('server-communication/ts/src/app/toh/hero.service.ts', 'create-sig')(format=".")
2016-05-13 16:32:54 -04:00
2015-12-01 06:15:14 -05:00
:marked
2016-10-20 02:17:50 -04:00
To implement it, you must know the server's API for creating heroes.
2017-03-09 15:54:14 -05:00
[This sample's data server](#in-mem-web-api) follows typical REST guidelines.
2015-12-01 06:15:14 -05:00
It expects a [`POST`](http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.5) request
2016-10-20 02:17:50 -04:00
at the same endpoint as `GET` heroes.
It expects the new hero data to arrive in the body of the request,
2015-12-01 06:15:14 -05:00
structured like a `Hero` entity but without the `id` property.
The body of the request should look like this:
2016-10-20 02:17:50 -04:00
2015-12-01 06:15:14 -05:00
code-example(format="." language="javascript").
{ "name": "Windstorm" }
:marked
2016-10-20 02:17:50 -04:00
The server generates the `id` and returns the entire `JSON` representation
2016-02-02 05:27:52 -05:00
of the new hero including its generated id. The hero arrives tucked inside a response object
with its own `data` property.
2016-10-20 02:17:50 -04:00
2017-03-14 13:48:21 -04:00
Now that you know how the API works, implement `create()` as follows:
2016-05-13 16:32:54 -04:00
2017-03-30 19:13:42 -04:00
+makeExample('server-communication/ts/src/app/toh/hero.service.ts', 'import-request-options', 'src/app/toh/hero.service.ts (additional imports)')(format=".")
2017-03-14 13:48:21 -04:00
+makeExcerpt('src/app/toh/hero.service.ts', 'create')
2016-05-13 16:32:54 -04:00
2017-03-09 15:54:14 -05:00
a#headers
2015-12-01 06:15:14 -05:00
:marked
2016-05-13 16:32:54 -04:00
### Headers
2016-10-20 02:17:50 -04:00
In the `headers` object, the `Content-Type` specifies that the body represents JSON.
2016-05-13 16:32:54 -04:00
2017-03-30 19:13:42 -04:00
:marked
Next, the `headers` object is used to configure the `options` object. The `options`
object is a new instance of `RequestOptions`, a class that allows you to specify
certain settings when instantiating a request. In this way, [headers](../api/http/index/Headers-class.html) is one of the [RequestOptions](../api/http/index/RequestOptions-class.html).
2016-05-13 16:32:54 -04:00
2017-03-30 19:13:42 -04:00
In the `return` statement, `options` is the *third* argument of the `post()` method, as shown above.
2016-02-01 22:52:14 -05:00
2017-03-09 15:54:14 -05:00
a#json-results
2016-02-01 22:52:14 -05:00
:marked
### JSON results
2016-05-13 16:32:54 -04:00
2017-03-30 19:13:42 -04:00
As with `getHeroes()`, use the `extractData()` helper to [extract the data](#extract-data)
2016-10-20 02:17:50 -04:00
from the response.
2016-05-13 16:32:54 -04:00
block hero-list-comp-add-hero
2016-02-01 22:52:14 -05:00
:marked
2017-03-14 13:48:21 -04:00
Back in the `HeroListComponent`, its `addHero()` method subscribes to the Observable returned by the service's `create()` method.
2016-10-20 02:17:50 -04:00
When the data arrive it pushes the new hero object into its `heroes` array for presentation to the user.
2017-02-02 13:38:17 -05:00
+makeExample('server-communication/ts/src/app/toh/hero-list.component.ts', 'addHero', 'src/app/toh/hero-list.component.ts (addHero)')(format=".")
2015-12-01 06:15:14 -05:00
2017-03-30 19:13:42 -04:00
h2#promises Fall back to promises
:marked
Although the Angular `http` client API returns an `Observable<Response>` you can turn it into a
[`Promise<Response>`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
It's easy to do, and in simple cases, a Promise-based version looks much
like the Observable-based version.
.l-sub-section
2016-01-28 04:22:59 -05:00
:marked
2017-03-30 19:13:42 -04:00
While Promises may be more familiar, Observables have many advantages.
2016-10-20 02:17:50 -04:00
2017-03-30 19:13:42 -04:00
:marked
Here is a comparison of the `HeroService` using Promises versus Observables,
highlighting just the parts that are different.
+makeTabs(
'server-communication/ts/src/app/toh/hero.service.promise.ts,server-communication/ts/src/app/toh/hero.service.ts',
'methods, methods',
'src/app/toh/hero.service.promise.ts (promise-based), src/app/toh/hero.service.ts (observable-based)')
:marked
You can follow the Promise `then(this.extractData).catch(this.handleError)` pattern as in
this example.
2016-05-13 16:32:54 -04:00
2017-03-30 19:13:42 -04:00
Alternatively, you can call `toPromise(success, fail)`. The Observable's `map` callback moves to the
first *success* parameter and its `catch` callback to the second *fail* parameter
in this pattern: `.toPromise(this.extractData, this.handleError)`.
2016-05-13 16:32:54 -04:00
2017-03-30 19:13:42 -04:00
The `errorHandler` forwards an error message as a failed `Promise` instead of a failed `Observable`.
2016-05-13 16:32:54 -04:00
2017-03-30 19:13:42 -04:00
The diagnostic *log to console* is just one more `then()` in the Promise chain.
2016-05-13 16:32:54 -04:00
2017-03-30 19:13:42 -04:00
You have to adjust the calling component to expect a `Promise` instead of an `Observable`:
2016-05-13 16:32:54 -04:00
2017-03-30 19:13:42 -04:00
+makeTabs(
'server-communication/ts/src/app/toh/hero-list.component.promise.ts, server-communication/ts/src/app/toh/hero-list.component.ts',
'methods, methods',
'src/app/toh/hero-list.component.promise.ts (promise-based), src/app/toh/hero-list.component.ts (observable-based)')
:marked
The only obvious difference is that you call `then()` on the returned Promise instead of `subscribe`.
Both methods take the same functional arguments.
.l-sub-section
2016-05-13 16:32:54 -04:00
:marked
2017-03-30 19:13:42 -04:00
The less obvious but critical difference is that these two methods return very different results.
2016-05-13 16:32:54 -04:00
2017-03-30 19:13:42 -04:00
The Promise-based `then()` returns another Promise. You can keep chaining
more `then()` and `catch()` calls, getting a new promise each time.
2016-05-13 16:32:54 -04:00
2017-03-30 19:13:42 -04:00
The `subscribe()` method returns a `Subscription`. A `Subscription` is not another `Observable`.
It's the end of the line for Observables. You can't call `map()` on it or call `subscribe()` again.
The `Subscription` object has a different purpose, signified by its primary method, `unsubscribe`.
2016-05-13 16:32:54 -04:00
2017-03-30 19:13:42 -04:00
To understand the implications and consequences of subscriptions,
watch [Ben Lesh's talk on Observables](https://www.youtube.com/watch?v=3LKMwkuK0ZE)
or his video course on [egghead.io](https://egghead.io/lessons/rxjs-rxjs-observables-vs-promises).
2016-05-13 16:32:54 -04:00
2016-10-24 05:57:19 -04:00
h2#cors Cross-Origin Requests: Wikipedia example
2015-12-01 06:15:14 -05:00
:marked
2017-03-30 19:13:42 -04:00
You just learned how to make `XMLHttpRequests` using the Angular <code>Http</code> service.
2017-03-14 13:48:21 -04:00
This is the most common approach to server communication, but it doesn't work in all scenarios.
2015-12-01 06:15:14 -05:00
2016-02-02 05:27:52 -05:00
For security reasons, web browsers block `XHR` calls to a remote server whose origin is different from the origin of the web page.
2016-10-20 02:17:50 -04:00
The *origin* is the combination of URI scheme, hostname, and port number.
This is called the [same-origin policy](https://en.wikipedia.org/wiki/Same-origin_policy).
2015-12-01 06:15:14 -05:00
.l-sub-section
:marked
2016-10-20 02:17:50 -04:00
Modern browsers do allow `XHR` requests to servers from a different origin if the server supports the
2016-02-02 05:27:52 -05:00
[CORS](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing) protocol.
2017-03-09 15:54:14 -05:00
If the server requires user credentials, enable them in the [request headers](#headers).
2015-12-01 06:15:14 -05:00
:marked
2016-02-02 05:27:52 -05:00
Some servers do not support CORS but do support an older, read-only alternative called [JSONP](https://en.wikipedia.org/wiki/JSONP).
Wikipedia is one such server.
.l-sub-section
:marked
2016-10-20 02:17:50 -04:00
This [Stack Overflow answer](http://stackoverflow.com/questions/2067472/what-is-jsonp-all-about/2067584#2067584) covers many details of JSONP.
2017-03-09 15:54:14 -05:00
a#search-wikipedia
2016-02-02 05:27:52 -05:00
:marked
2017-03-09 15:54:14 -05:00
### Search Wikipedia
2016-10-20 02:17:50 -04:00
Here is a simple search that shows suggestions from Wikipedia as the user
types in a text box:
2016-05-13 16:32:54 -04:00
2015-12-01 06:15:14 -05:00
figure.image-display
img(src='/resources/images/devguide/server-communication/wiki-1.gif' alt="Wikipedia search app (v.1)" width="250")
2016-05-13 16:32:54 -04:00
block wikipedia-jsonp+
:marked
2016-10-20 02:17:50 -04:00
Wikipedia offers a modern `CORS` API and a legacy `JSONP` search API. This example uses the latter.
2017-03-30 19:13:42 -04:00
The Angular `Jsonp` service both extends the `Http` service for JSONP and restricts you to `GET` requests.
2017-03-09 15:54:14 -05:00
All other HTTP methods throw an error because `JSONP` is a read-only facility.
2015-12-01 06:15:14 -05:00
2016-10-20 02:17:50 -04:00
As always, wrap the interaction with an Angular data access client service inside a dedicated service, here called `WikipediaService`.
2015-12-01 06:15:14 -05:00
2017-02-02 13:38:17 -05:00
+makeExample('server-communication/ts/src/app/wiki/wikipedia.service.ts',null,'src/app/wiki/wikipedia.service.ts')
2016-02-02 05:27:52 -05:00
:marked
2017-03-30 17:41:23 -04:00
The constructor expects Angular to inject its `Jsonp` service, which
2016-10-20 02:17:50 -04:00
is available because `JsonpModule` is in the root `@NgModule` `imports` array
in `app.module.ts`.
2016-05-13 16:32:54 -04:00
<a id="query-parameters"></a>
:marked
### Search parameters
2016-10-20 02:17:50 -04:00
The [Wikipedia "opensearch" API](https://www.mediawiki.org/wiki/API:Opensearch)
2016-05-13 16:32:54 -04:00
expects four parameters (key/value pairs) to arrive in the request URL's query string.
The keys are `search`, `action`, `format`, and `callback`.
The value of the `search` key is the user-supplied search term to find in Wikipedia.
The other three are the fixed values "opensearch", "json", and "JSONP_CALLBACK" respectively.
.l-sub-section
:marked
2016-10-20 02:17:50 -04:00
The `JSONP` technique requires that you pass a callback function name to the server in the query string: `callback=JSONP_CALLBACK`.
The server uses that name to build a JavaScript wrapper function in its response, which Angular ultimately calls to extract the data.
2016-05-13 16:32:54 -04:00
All of this happens under the hood.
2015-12-01 06:15:14 -05:00
:marked
2016-10-20 02:17:50 -04:00
If you're looking for articles with the word "Angular", you could construct the query string by hand and call `jsonp` like this:
2017-02-02 13:38:17 -05:00
+makeExample('server-communication/ts/src/app/wiki/wikipedia.service.1.ts','query-string')(format='.')
2016-05-13 16:32:54 -04:00
:marked
2016-10-20 02:17:50 -04:00
In more parameterized examples you could build the query string with the Angular `URLSearchParams` helper:
2017-02-02 13:38:17 -05:00
+makeExample('server-communication/ts/src/app/wiki/wikipedia.service.ts','search-parameters','src/app/wiki/wikipedia.service.ts (search parameters)')(format=".")
2016-05-13 16:32:54 -04:00
:marked
2016-10-20 02:17:50 -04:00
This time you call `jsonp` with *two* arguments: the `wikiUrl` and an options object whose `search` property is the `params` object.
2017-02-02 13:38:17 -05:00
+makeExample('server-communication/ts/src/app/wiki/wikipedia.service.ts','call-jsonp','src/app/wiki/wikipedia.service.ts (call jsonp)')(format=".")
2016-05-13 16:32:54 -04:00
:marked
2017-03-30 17:41:23 -04:00
`Jsonp` flattens the `params` object into the same query string you saw earlier, sending the request
2017-03-09 15:54:14 -05:00
to the server.
2015-12-01 06:15:14 -05:00
2016-05-13 16:32:54 -04:00
<a id="wikicomponent"></a>
:marked
### The WikiComponent
2015-12-01 06:15:14 -05:00
2017-01-05 04:12:06 -05:00
Now that you have a service that can query the Wikipedia API,
turn your attention to the component (template and class) that takes user input and displays search results.
2017-02-02 13:38:17 -05:00
+makeExample('server-communication/ts/src/app/wiki/wiki.component.ts', null, 'src/app/wiki/wiki.component.ts')
2016-05-13 16:32:54 -04:00
:marked
2016-10-20 02:17:50 -04:00
The template presents an `<input>` element *search box* to gather search terms from the user,
2016-05-13 16:32:54 -04:00
and calls a `search(term)` method after each `keyup` event.
2017-01-05 04:12:06 -05:00
2017-03-30 19:13:42 -04:00
The component's `search(term)` method delegates to the `WikipediaService`, which returns an
Observable array of string results (`Observable<string[]>`).
2017-03-09 15:54:14 -05:00
Instead of subscribing to the Observable inside the component, as in the `HeroListComponent`,
2017-03-30 17:41:23 -04:00
the app forwards the Observable result to the template (via `items`) where the `async` pipe
2016-10-20 02:17:50 -04:00
in the `ngFor` handles the subscription. Read more about [async pipes](pipes.html#async-pipe)
in the [Pipes](pipes.html) page.
2016-05-13 16:32:54 -04:00
.l-sub-section
:marked
2017-03-30 17:41:23 -04:00
The [async pipe](pipes.html#async-pipe) is a good choice in read-only components
2017-03-09 15:54:14 -05:00
where the component has no need to interact with the data.
2016-10-20 02:17:50 -04:00
`HeroListComponent` can't use the pipe because `addHero()` pushes newly created heroes into the list.
2017-03-09 15:54:14 -05:00
a#wasteful-app
2016-05-13 16:32:54 -04:00
:marked
2016-10-20 02:17:50 -04:00
## A wasteful app
2016-05-13 16:32:54 -04:00
2017-03-09 15:54:14 -05:00
The Wikipedia search makes too many calls to the server.
It is inefficient and potentially expensive on mobile devices with limited data plans.
2016-05-13 16:32:54 -04:00
### 1. Wait for the user to stop typing
2017-01-05 04:12:06 -05:00
Presently, the code calls the server after every keystroke.
2017-03-09 15:54:14 -05:00
It should only make requests when the user *stops typing*.
2016-10-20 02:17:50 -04:00
Here's how it will work after refactoring:
2016-05-13 16:32:54 -04:00
figure.image-display
img(src='/resources/images/devguide/server-communication/wiki-2.gif' alt="Wikipedia search app (v.2)" width="250")
:marked
### 2. Search when the search term changes
2016-10-20 02:17:50 -04:00
Suppose a user enters the word *angular* in the search box and pauses for a while.
The application issues a search request for *angular*.
2016-05-13 16:32:54 -04:00
Then the user backspaces over the last three letters, *lar*, and immediately re-types *lar* before pausing once more.
2016-10-20 02:17:50 -04:00
The search term is still _angular_. The app shouldn't make another request.
2016-05-13 16:32:54 -04:00
### 3. Cope with out-of-order responses
2016-10-20 02:17:50 -04:00
The user enters *angular*, pauses, clears the search box, and enters *http*.
The application issues two search requests, one for *angular* and one for *http*.
2016-05-13 16:32:54 -04:00
2016-10-20 02:17:50 -04:00
Which response arrives first? It's unpredictable.
2016-05-13 16:32:54 -04:00
When there are multiple requests in-flight, the app should present the responses
2017-03-30 17:41:23 -04:00
in the original request order.
2017-01-05 04:12:06 -05:00
In this example, the app must always display the results for the *http* search
no matter which response arrives first.
2016-05-13 16:32:54 -04:00
<a id="more-observables"></a>
2017-03-09 15:54:14 -05:00
## More fun with Observables
2016-05-13 16:32:54 -04:00
2016-10-20 02:17:50 -04:00
You could make changes to the `WikipediaService`, but for a better
2017-01-05 04:12:06 -05:00
user experience, create a copy of the `WikiComponent` instead and make it smarter,
2017-03-09 15:54:14 -05:00
with the help of some nifty Observable operators.
2017-01-05 04:12:06 -05:00
2017-03-09 15:54:14 -05:00
Here's the `WikiSmartComponent`, shown next to the original `WikiComponent`:
2017-01-05 04:12:06 -05:00
+makeTabs(
2017-02-02 13:38:17 -05:00
`server-communication/ts/src/app/wiki/wiki-smart.component.ts,
2017-03-30 17:41:23 -04:00
server-communication/ts/src/app/wiki/wiki.component.ts`,
null,
2017-02-02 13:38:17 -05:00
`src/app/wiki/wiki-smart.component.ts,
src/app/wiki/wiki.component.ts`
2017-01-05 04:12:06 -05:00
)
:marked
While the templates are virtually identical,
2017-03-30 17:41:23 -04:00
there's a lot more RxJS in the "smart" version,
2017-01-05 04:12:06 -05:00
starting with `debounceTime`, `distinctUntilChanged`, and `switchMap` operators,
2017-03-09 15:54:14 -05:00
imported as [described above](#rxjs-library).
2016-05-13 16:32:54 -04:00
2017-03-09 15:54:14 -05:00
a#create-stream
:marked
2016-05-13 16:32:54 -04:00
### Create a stream of search terms
2017-01-05 04:12:06 -05:00
The `WikiComponent` passes a new search term directly to the `WikipediaService` after every keystroke.
2017-03-09 15:54:14 -05:00
The `WikiSmartComponent` class turns the user's keystrokes into an Observable _stream of search terms_
2017-01-05 04:12:06 -05:00
with the help of a `Subject`, which you import from RxJS:
2017-02-02 13:38:17 -05:00
+makeExample('server-communication/ts/src/app/wiki/wiki-smart.component.ts', 'import-subject')(format='.')
2016-05-13 16:32:54 -04:00
:marked
2016-10-20 02:17:50 -04:00
The component creates a `searchTermStream` as a `Subject` of type `string`.
2017-03-09 15:54:14 -05:00
The `search()` method adds each new search box value to that stream via the subject's `next()` method.
2016-10-20 02:17:50 -04:00
2017-02-02 13:38:17 -05:00
+makeExample('server-communication/ts/src/app/wiki/wiki-smart.component.ts', 'subject')(format='.')
2017-03-30 17:41:23 -04:00
2017-03-09 15:54:14 -05:00
a#listen-for-search-terms
2016-05-13 16:32:54 -04:00
:marked
### Listen for search terms
2017-03-30 17:41:23 -04:00
The `WikiSmartComponent` listens to the *stream of search terms* and
2017-01-05 04:12:06 -05:00
processes that stream _before_ calling the service.
2017-02-02 13:38:17 -05:00
+makeExample('server-communication/ts/src/app/wiki/wiki-smart.component.ts', 'observable-operators')(format='.')
2017-01-05 04:12:06 -05:00
:marked
* <a href="https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/debounce.md" target="_blank" title="debounce operator"><i>debounceTime</i></a>
waits for the user to stop typing for at least 300 milliseconds.
2016-05-13 16:32:54 -04:00
2017-01-05 04:12:06 -05:00
* <a href="https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/distinctuntilchanged.md" target="_blank" title="distinctUntilChanged operator"><i>distinctUntilChanged</i></a>
ensures that the service is called only when the new search term is different from the previous search term.
2016-10-20 02:17:50 -04:00
2017-01-05 04:12:06 -05:00
* The <a href="https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/flatmaplatest.md" target="_blank" title="switchMap operator"><i>switchMap</i></a>
calls the `WikipediaService` with a fresh, debounced search term and coordinates the stream(s) of service response.
2016-05-13 16:32:54 -04:00
2017-01-05 04:12:06 -05:00
The role of `switchMap` is particularly important.
2017-03-09 15:54:14 -05:00
The `WikipediaService` returns a separate Observable of string arrays (`Observable<string[]>`) for each search request.
2017-01-05 04:12:06 -05:00
The user could issue multiple requests before a slow server has had time to reply,
2017-03-09 15:54:14 -05:00
which means a backlog of response Observables could arrive at the client, at any moment, in any order.
2016-05-13 16:32:54 -04:00
2017-03-09 15:54:14 -05:00
The `switchMap` returns its own Observable that _combines_ all `WikipediaService` response Observables,
2016-05-13 16:32:54 -04:00
re-arranges them in their original request order,
2016-10-20 02:17:50 -04:00
and delivers to subscribers only the most recent search results.
2015-12-01 06:15:14 -05:00
2016-10-24 05:57:19 -04:00
a#xsrf
.l-main-section
:marked
## Guarding against Cross-Site Request Forgery
In a cross-site request forgery (CSRF or XSRF), an attacker tricks the user into visiting
2017-03-09 15:54:14 -05:00
a different web page with malignant code that secretly sends a malicious request to your application's web server.
2017-03-30 17:41:23 -04:00
2016-10-24 05:57:19 -04:00
The server and client application must work together to thwart this attack.
Angular's `Http` client does its part by applying a default `CookieXSRFStrategy` automatically to all requests.
The `CookieXSRFStrategy` supports a common anti-XSRF technique in which the server sends a randomly
2017-03-30 17:41:23 -04:00
generated authentication token in a cookie named `XSRF-TOKEN`.
The HTTP client adds an `X-XSRF-TOKEN` header with that token value to subsequent requests.
2016-10-24 05:57:19 -04:00
The server receives both the cookie and the header, compares them, and processes the request only if the cookie and header match.
2017-03-30 17:41:23 -04:00
2016-10-24 05:57:19 -04:00
See the [XSRF topic on the Security page](security.html#xsrf) for more information about XSRF and Angular's `XSRFStrategy` counter measures.
2016-12-14 16:30:25 -05:00
a#override-default-request-options
.l-main-section
:marked
## Override default request headers (and other request options)
Request options (such as headers) are merged into the
2017-03-30 17:41:23 -04:00
[default _RequestOptions_](https://angular.io/docs/ts/latest/api/http/index/BaseRequestOptions-class.html "API: BaseRequestOptions")
2016-12-14 16:30:25 -05:00
before the request is processed.
The `HttpModule` provides these default options via the `RequestOptions` token.
2017-03-09 15:54:14 -05:00
You can override these defaults to suit your application needs
2016-12-14 23:35:29 -05:00
by creating a custom sub-class of `RequestOptions`
that sets the default options for the application.
2016-12-14 16:30:25 -05:00
2016-12-14 23:35:29 -05:00
This sample creates a class that sets the default `Content-Type` header to JSON.
It exports a constant with the necessary `RequestOptions` provider to simplify registration in `AppModule`.
2017-02-02 13:38:17 -05:00
+makeExample('server-communication/ts/src/app/default-request-options.service.ts', '', 'src/app/default-request-options.service.ts')(format=".")
2016-12-14 23:35:29 -05:00
:marked
Then it registers the provider in the root `AppModule`.
2017-02-02 13:38:17 -05:00
+makeExample('server-communication/ts/src/app/app.module.ts', 'provide-default-request-options', 'src/app/app.module.ts (provide default request header)')(format=".")
2016-12-14 23:35:29 -05:00
.l-sub-section
:marked
Remember to include this provider during setup when unit testing the app's HTTP services.
2016-12-14 16:30:25 -05:00
:marked
2017-03-14 13:48:21 -04:00
After this change, the `header` option setting in `HeroService.create()` is no longer necessary,
2016-12-14 16:30:25 -05:00
2017-03-14 13:48:21 -04:00
+makeExcerpt('src/app/toh/hero.service.ts', 'create')
2016-12-14 16:30:25 -05:00
:marked
2016-12-14 23:35:29 -05:00
You can confirm that `DefaultRequestOptions` is working by examing HTTP requests in the browser developer tools' network tab.
2016-12-14 16:30:25 -05:00
If you're short-circuiting the server call with something like the [_in-memory web api_](#in-mem-web-api),
2017-03-30 17:41:23 -04:00
try commenting-out the `create` header option,
2016-12-14 23:35:29 -05:00
set a breakpoint on the POST call, and step through the request processing
2016-12-14 16:30:25 -05:00
to verify the header is there.
2017-03-30 17:41:23 -04:00
2016-12-14 16:30:25 -05:00
Individual requests options, like this one, take precedence over the default `RequestOptions`.
2017-03-14 13:48:21 -04:00
It might be wise to keep the `create` request header setting for extra safety.
2016-12-14 16:30:25 -05:00
2016-05-13 16:32:54 -04:00
a#in-mem-web-api
2015-12-01 06:15:14 -05:00
.l-main-section
:marked
2016-12-14 16:30:25 -05:00
## Appendix: Tour of Heroes _in-memory web api_
2015-12-01 06:15:14 -05:00
2016-10-20 02:17:50 -04:00
If the app only needed to retrieve data, you could get the heroes from a `heroes.json` file:
2017-03-30 19:13:42 -04:00
+makeJson('server-communication/ts/src/app/heroes.json', null, 'src/app/heroes.json')(format=".")
2015-12-01 06:15:14 -05:00
.l-sub-section
:marked
2016-10-20 02:17:50 -04:00
You wrap the heroes array in an object with a `data` property for the same reason that a data server does:
2015-12-01 06:15:14 -05:00
to mitigate the [security risk](http://stackoverflow.com/questions/3503102/what-are-top-level-json-arrays-and-why-are-they-a-security-risk)
2016-10-20 02:17:50 -04:00
posed by top-level JSON arrays.
2015-12-01 06:15:14 -05:00
:marked
2016-10-20 02:17:50 -04:00
You'd set the endpoint to the JSON file like this:
2017-02-02 13:38:17 -05:00
+makeExample('server-communication/ts/src/app/toh/hero.service.ts', 'endpoint-json', 'src/app/toh/hero.service.ts')(format=".")
2016-05-13 16:32:54 -04:00
2016-02-17 12:13:57 -05:00
:marked
2016-10-20 02:17:50 -04:00
The *get heroes* scenario would work,
but since the app can't save changes to a JSON file, it needs a web API server.
2017-03-30 17:41:23 -04:00
Because there isn't a real server for this demo,
2016-12-13 05:18:07 -05:00
it substitutes the Angular _in-memory web api_ simulator for the actual XHR backend service.
2016-05-13 16:32:54 -04:00
2016-05-03 10:26:09 -04:00
.l-sub-section
:marked
2017-03-30 17:41:23 -04:00
The in-memory web api is not part of Angular _proper_.
It's an optional service in its own
2016-12-13 05:18:07 -05:00
<a href="https://github.com/angular/in-memory-web-api" target="_blank" title="In-memory Web API"><i>angular-in-memory-web-api</i></a>
library installed with npm (see `package.json`).
See the
<a href="https://github.com/angular/in-memory-web-api/blob/master/README.md" target="_blank" title='In-memory Web API "README.md"'><i>README file</i></a>
for configuration options, default behaviors, and limitations.
2016-05-13 16:32:54 -04:00
2015-12-01 06:15:14 -05:00
:marked
2017-03-30 19:13:42 -04:00
The in-memory web API gets its data from a custom application class with a `createDb()`
2016-10-20 02:17:50 -04:00
method that returns a map whose keys are collection names and whose values
2017-03-30 19:13:42 -04:00
are arrays of objects in those collections.
2016-10-20 02:17:50 -04:00
Here's the class for this sample, based on the JSON data:
2017-02-02 13:38:17 -05:00
+makeExample('server-communication/ts/src/app/hero-data.ts', null, 'src/app/hero-data.ts')(format=".")
2015-12-01 06:15:14 -05:00
:marked
2016-05-13 16:32:54 -04:00
Ensure that the `HeroService` endpoint refers to the web API:
2017-02-02 13:38:17 -05:00
+makeExample('server-communication/ts/src/app/toh/hero.service.ts', 'endpoint', 'src/app/toh/hero.service.ts')(format=".")
2016-10-20 02:17:50 -04:00
2016-05-13 16:32:54 -04:00
block redirect-to-web-api
:marked
2016-10-20 02:17:50 -04:00
Finally, redirect client HTTP requests to the in-memory web API by
adding the `InMemoryWebApiModule` to the `AppModule.imports` list.
2017-03-09 15:54:14 -05:00
At the same time, call its `forRoot()` configuration method with the `HeroData` class.
2017-02-02 13:38:17 -05:00
+makeExample('server-communication/ts/src/app/app.module.ts', 'in-mem-web-api', 'src/app/app.module.ts')(format=".")
2016-08-19 07:23:55 -04:00
:marked
### How it works
Angular's `http` service delegates the client/server communication tasks
2016-10-20 02:17:50 -04:00
to a helper service called the `XHRBackend`.
2016-05-13 16:32:54 -04:00
2016-10-20 02:17:50 -04:00
Using standard Angular provider registration techniques, the `InMemoryWebApiModule`
replaces the default `XHRBackend` service with its own in-memory alternative.
At the same time, the `forRoot` method initializes the in-memory web API with the *seed data* from the mock hero dataset.
2016-08-19 07:23:55 -04:00
.l-sub-section
:marked
2017-03-09 15:54:14 -05:00
The `forRoot()` method name is a strong reminder that you should only call the `InMemoryWebApiModule` _once_,
2016-10-20 02:17:50 -04:00
while setting the metadata for the root `AppModule`. Don't call it again.
2016-07-03 20:11:17 -04:00
:marked
2017-03-30 19:13:42 -04:00
Here is the final, revised version of <code>src/app/app.module.ts</code>, demonstrating these steps.
2016-05-13 16:32:54 -04:00
2017-02-02 13:38:17 -05:00
+makeExcerpt('src/app/app.module.ts')
2016-10-20 02:17:50 -04:00
.alert.is-important
:marked
2017-03-30 17:41:23 -04:00
Import the `InMemoryWebApiModule` _after_ the `HttpModule` to ensure that
2016-10-20 02:17:50 -04:00
the `XHRBackend` provider of the `InMemoryWebApiModule` supersedes all others.
2016-07-03 20:11:17 -04:00
:marked
See the full source code in the <live-example></live-example>.