Whew! We already learned quite a lot about how Angular 2 works. One thing that we haven't looked into yet is how to
communicate with a backend. Most applications will come to a point where they either want to read from or write to
a remote location. Angular 2 has excellent support for such scenarios so let's dive right into it.
Try the [live example](/resources/live-examples/server-communication/ts/plnkr.html).
.l-main-section
:marked
## The Basics
When we look at the broad task of connecting multiple devices to talk to each other, there really are plenty of different options.
If we zoom in a little and restrict us to only look at the options that allow a web application that runs in a browser to communicate with
a backend we are basically left with communication via the [`HTTP`](https://tools.ietf.org/html/rfc2616) or [`WebSocket`](https://tools.ietf.org/html/rfc6455) protocol.
For web apps to communicate via `HTTP` there are basically two different techniques which are `XMLHttpRequest (XHR)` and `JSONP`.
They are quite different from each other both in purpose and implementation.
Angular comes with its own built-in abstractions that allow us to exploit both techniques in a nicely well integrated way.
## Http Client
We use the Angular `Http` client to communicate via `XMLHttpRequest (XHR)`.
We'll illustrate with a mini-version of the [tutorial](tutorial.html)'s "Tour of Heroes" (ToH) application.
This one gets some heroes from the server, displays them in a list, lets us add new heroes, and save them to the server.
It works like this.
figure.image-display
img(src='/resources/images/devguide/server-communication/http-toh.gif' alt="ToH mini app" width="250")
:marked
It's implemented with two components — a parent `TohComponent` shell and the `HeroListComponent` child.
We've seen these kinds of component in many other documentation samples.
Let's see how they change to support communication with a server.
.l-sub-section
:marked
We're overdoing the "separation of concerns" by creating two components for a tiny demo.
We're making a point about application structure that is easier to justify when the app grows.
We just learned how to make `XMLHttpRequests` using Angulars built-in `Http` service. This is the most common approach for
server Communication. It doesn't work in all scenarios though.
For security reasons web browser do not permit to make `XHR` calls if the origin of the remote server is different from the one the web page runs in.
The origin is defined as the combination of URI scheme, hostname and port number. The policy that prevents such `XHR` requests is called [Same-origin Policy](https://en.wikipedia.org/wiki/Same-origin_policy) accordingly.
.l-sub-section
:marked
That's not entirely true. Modern browsers do allow `XHR` requests against foreign origins if the server sends the appropriate [CORS](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing) headers.
In such cases there's nothing specific to do for the client unless we want our `XHR` request to include credentials (e.g Cookies) which we then have to explicitly enable for the request.
:marked
But let's not go too deep into the rabbit hole of `JSONP`. If you like to learn how this technique works under the cover, you may like to read up on this [answer](http://stackoverflow.com/questions/2067472/what-is-jsonp-all-about/2067584#2067584) on StackOverflow.
For now, let's focus on how we can use `JSONP` in Angular.
### Let's fetch some data from wikipedia
Wikipedia offers a `JSONP` search api. Let's build a simple search that shows suggestions from wikipedia as we type in a text box.
Angular provides us with a `Jsonp` services which has the same API surface as the `Http` service with the only difference that it restricts us to use `GET` requests only. This is
because the nature of `JSONP` does not allow any other kind of requests. In order to use the `Jsonp` service we have to specify the `JSONP_PROVIDERS`.
Again, we'll make sure to do the server communication in a dedicated service that we call `WikipediaService`.
There shouldn't be much of a surprise here. Our component defines an `<input>` and calls a `search(term)` method for each `keyup` event.
The `search(term)` method delegates to our `WikipediaService` which returns an `Observable<Array<string>>` to us. Instead of subscribing to it
manually we use the [async pipe](pipes.html#async-pipe) in the `ngFor` to let the view subscribe to the Observable directly.
.l-sub-section
:marked
As a rule of thumb we can use the [async pipe](pipes.html#async-pipe) whenever we don't need to interact with the unwrapped payload from the `Observable`/`Promise`
other than from the view directly. In our previous example we couldn't use it since we needed to keep a reference to the bare array of heros so that we can push
new objects into the array as we create new heros.
:marked
There are a bunch of things in our wikipedia demo that we could do better. This is a perfect opportunity to show off some nifty
`Observable` tricks that can make server communication much simpler and more fun.
## Taking advantage of Observables
If you ever wrote a search-as-you-type control yourself before, you are probably aware of some typical corner cases that arise with this task.
### 1. Don't hit the search endpoint on every key stroke
Treat the search endpoint as if you pay for it on a per-request basis. No matter if it's your own hardware or not. We shouldn't be hammering
the search enpoint more often than needed.
What we want is to hit the search endpoint as soon as the user *stops typing* instead of after every keystroke.
Here's how it *should* work — and *will* work — when we're done refactoring:
### 2. Don't hit the search endpoint for the same term again
Consider you type *foo*, stop, type another *o*, hit return and stop back at *foo*. That should be just one request with the term *foo*
and not two even if we technically stopped twice after we had *foo* in the search box.
### 3. Cope with out-of-order responses
When we have multiple requests in-flight at the same time we must account for cases where they come back in unexpected order. Consider we first typed
*computer*, stop, a request goes out, we type *car*, stop, a request goes out but then the request that carries the results for *computer* comes back
after the request that carries the results for *car*. If we don't deal with such cases properly we can get a buggy application that shows
results for *computer* even if the search box reads *car*.
Now that we identified the problems that need to be solved, let's make a couple of trivial changes to our code to fix them in a *functional reactive* way. Here is the
entire example with all changes.
There are no changes for our `WikipediaService` so we can skip that one. We'll go over each change to briefly describe what
The first thing we need to do to unveil the full magic of a observable-based solution is to get an `Observable<string>` for our `<input>` control.
The best way to do that is to change `<input #term (keyup)="search(term.value)"/>` into `<input [ng-form-control]="inputs"/>` and to create an `inputs` `Control` accordingly.
We now have an `Observable<string>` at `this.inputs.valueChanges`. We can simply use the `debounceTime(ms)` and `distinctUntilChanged()` operators to fix the first two problems. We basically get a new `Observable<string>` that emits
new values exactly the way we want them to be emitted.
With the previous change we tamed the input but we still need to deal with the out-of-order cases. At this point we have an `Observable<string>` and a
`search(term)` method on the `WikipediaService` that returns an `Observable<Array<string>>`. What we want is an `Observable<Array<string>>` that
carries the results of the *last* term that was emitted from the `Observable<string>`.
If we would just map our current `Observable<string>` like `.map(term => wikipediaService.search(term))` we would transform it into an `Observable<Observable<Array<string>>`
which isn't quite what we want. Enter [`switchMap`](https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/flatmaplatest.md) to the rescue. Basically `switchMap` flattens from an `Observable<Observable<T>` into an `Observable<T>` by
emitting values only from the most recent `Observable<T>` that was produced from the outer `Observable`.
This may sound a lot like black magic for people unfamiliar with Observables but as soon as the coin sinks in it's starting to make a whole world of difficult programming tasks appear much simpler.
<a id="server"></a>
.l-main-section
:marked
## Appendix: Tour of Heroes in-memory server
If we only cared to retrieve data, we could tell Angular to get the heroes from a `heroes.json` file like this one: