Software systems to innovate and grow

How to Talk to Backend Services with Angular 2’s HTTP Client

By Engineering Team March 29, 2017 10 mins read

In this article, you’ll learn how to connect your Angular application to a backend service or API.

You’ll learn about –

  • The HTTP protocol and how our application will use it to communicate with the server.
  • Observables and how you can use them to make async requests.
  • A teeny tiny bit of RxJS – map, and catch.
  • Angular’s HTTP service.
  • Protecting your app from CSRF (Cross Site Request Forgery).

By the end of this article, your application will show users “real data” from your servers, and you will know a little bit more about how your Angular app communicates with the server.

How Computers Talk – Communication Protocol

Josh: “Sup?”

Andrew: “Going to new Star Wars movie, they shipping free life-size clones to the 1st 10 people who make it there!”

Josh: “OMG! I’m on my way!”

Andrew: “Kk. I need to register your name and address. Send me your details”

Josh: “My details are ….”

That’s what a conversation between two humans might look like. The word “sup” isn’t really an English word, neither is “Kk” or “OMG”.

But that’s not a problem for Josh and Andrew, they understand it.

But what if that same conversation took place between computers –

C203: “Sup?”

CP30: “ERROR! Unrecognized message format!”

Computers need a more structured way to communicate. Computers need protocols – standards established for computers to communicate.

There are many different protocols used over the internet and they serve different purposes. Most of these protocols work together as “stacks.”

A single request to a web server may utilize the Ethernet, TCP/IP, and the HTTP protocol.

We aren’t going to dive deep into all these protocols, but you can read more about them here.

The one that we care about most is HTTP.

HTTP – Hyper Text Transfer Protocol

HTTP is how our application will communicate with the server.

Browsers mainly use these HTTP-based APIs to make requests to the server –

  1. XMLHttpRequest – it provides functionality for retrieving data from a server without doing a full page refresh.
  2. JsonP – works differently from the XMLHttpRequest API and allows us to execute cross domain requests.
  3. Fetch – similar to XMLHttpRequest but the fetch API works with promises. (Not used in the Angular HTTP library).

Here’s the good news – we don’t have to worry about any of these APIs because the Angular team has taken care of the dirty work and given us the Angular HTTP Library.

Quick Note on HTTPS and WebSocket

HTTPS (Hypertext Transfer Protocol over Secured Socket Layer) is a related protocol that you can think of as HTTP with encryption – it’s more secure.

You may have heard of WebSockets every time you looked up “chat”. The WebSocket protocol uses HTTP for the initial handshake and then opens a bidirectional connection. This means that the server and the client can send data across without the additional overhead that comes with an HTTP request (such as HTTP headers).

The WebSocket protocol is useful for applications that require real-time data but not so useful for applications such as news pages where the user is on the page for extended periods of time without much interaction.

Observables – #$@&!

That’s the first thing that came to my mind when I heard about Observables. I had already spent so much time understanding Promises and how to use them – and now I need to learn something new just to make a little call to an API!

If you’re thinking like I was, take a deep breath and look at this.

Hmmm… Not that different.

If you’re working with Angular, you’ve probably come across Observables at some point. The Angular team really likes reactive programming and they promote it throughout the Angular framework (you can “subscribe” to your forms too).

What are Observables – Quick Dive

You just went on Amazon and ordered a new tech book to take your skills to the next level. You’re waiting anxiously for your book and you want updates as they occur.

Without Observables, here’s what you’d have to do.

Every time you’d like an update on the status of your shipment, you’d have to ride over to the Amazon fulfillment center and ask the kind old lady sitting behind the big brown desk –

You: “Is my book there yet?”

Then you’d have to wait a while as she slowly flipped through her records and retrieved the status of your package. Finally, you’d get your answer –

Old Lady: “It’s going to take another few days.”

You: “$^&#@! Fine… I’ll come back in a few days!!!”

Now let’s take a look at the situation with Observables.

You go to your notification preferences on Amazon and subscribe to tracking updates. Every time your shipment makes progress, Amazon will notify you.

You: “So easy? :/”

Observables make life a whole lot easier.

Post Office + Subscriber = Observer Pattern

An Observable sends notifications to its Observers by calling the Observer’s methods (look at the 3 methods section below).

RxJS implements the Observable pattern and gives us a bunch of operators to use with it to make asynchronous coding a whole lot better.

Angular’s HTTP Service uses RxJS and the Observer Pattern for HTTP requests.

Why Change to Observables

No, this isn’t just because it’s something that sounds cool and requires you to get your head around a new concept. Observables are better than Promises.

  1. Observables can be canceled – this makes them good for working with handling ongoing input events such as those created by auto-complete features.
  2. Observables can handle multiple values over time – which means you can use observables to work with real-time data streams.

Observers – The 3 Methods

There are three functions that can be passed to the subscribe method when creating the observer.

  1. onNext() – this is the method that is called when the Observable calls the next() method on the observer.
  2. onError() – this is the method that gets invoked either when the Observable calls the error() method or when any error is thrown in the process.
  3. onComplete() – the Observable can call the complete() method which ends the subscription of that observer.
The output of this will be –
For the most part, you’ll be dealing with the onNext() and the onError() methods.


Operators are what make RxJS so powerful. They are functions that take a source Observable and return a result Observable.

The process is pure and the Observable processed is immutable – which means that the source Observable remains untouched.

RxMarbles provides some great visualizations of the map, catch and other operators and really helps understand the concepts better. I highly recommend you spend a few minutes there.

Let’s look at the two operators we’ll be using.

RxJS – Map Operator

The map operator applies a function to each of the items emitted by the Observable.

The observable iterates the count and calls the subscriber’s nextFn. After 5 seconds, the observer unsubscribes from the stream.

The map function simply squares the value of the current item.

The output for the code above is.

RxJS – Catch Operator

The catch operator is for (you guessed it) error handling. You might be thinking at this point – isn’t that what the onError() function is for?

The catch operator is special. It continues an Observable sequence with another Observable sequence. The catch operator can be used to display error messages formatted for the user or even to log error messages to a server.

Here, the catch operator intercepts the error and gives the observer another Observable to continue with.

After the new Observable has done its job, it calls the completed() method that gets executed on the original observer.

The output of the code above.

Now you know everything you need to know to make Angular’s Http client easy to understand.

Angular’s HTTP Service

Get The Code

It’s easy for you to get the code and get started.

The app should be live on http://localhost:4200 and you’re ready to go!

Now let’s use Angular 2’s Http Client to fetch some data.

First, we need to make sure that the module has imported the Http module.

Now we’ve got everything set up in the module.

We don’t want any of the code for interaction with the backend service to be in a Component. All that code needs to live in a Service (if you’re wondering why it’s because the component shouldn’t know anything about retrieving the data. It’s only job is to display the data – dumb components are good components).

Let’s look at all the libraries we’ve imported –

  1. Injectable – needed to create the service.
  2. Http – required to make HTTP requests.
  3. Response – response object that is returned from the HTTP request.
  4. Headers – headers object that can be configured and passed with every HTTP request.
  5. RequestOptions – object that holds all the configuration and passed as an argument to the HTTP request.

After that, we’ve imported RxJS’ Observable and the two operators we’re going to be working with. RxJS is a large library so it’s important that we only import the operators we need.

Finally, we import the Post object which is the data model for the Posts.

Now let’s flesh out our service.

The service is pretty simple. Let’s just spend a second on the map operator used here.

The data we receive from the HTTP request through Angular 2’s http client is in the form of a string. The data needs to be converted to JSON for it to be rendered correctly by our component.

The catch method is pretty straightforward. We don’t have any logging or any error handling. All we do is convert the error message to a string and display that to the user.

Now let’s render all this in a component.

The most important thing to notice in this component is that we retrieve the data in the ngOnInit method instead of the constructor. This keeps the code clean and makes the application easier to debug. The constructor should always be as light as possible.

The getPosts method is where the subscription magic happens. We subscribe to the PostService’s getPosts stream and add the posts to our local scope when the posts are retrieved (and processed by the map function).

All the data gets rendered in this simple template.

Latest Posts









Awesome! We just configured our application to communicate with a backend service.

POST, PUT, and DELETE Requests with Angular 2’s Http Client

Of course, we aren’t going to skip the other HTTP verbs. Let’s use the jsonplaceholder web API again to make some more cool requests.

Note that the dummy API we’re using doesn’t actually create a record on the server. It only acts as though a record has been created.

POST Request

The post request has a few new things. To use this, we need –

  • A form to enter the data to be posted.
  • A method in the component to be triggered on form submit.
  • A method in the service to submit the form to the API.
  • We need to handle the response if the post request was made successfully.

Here’s a simple form. You could create this form however you want.

Next, we’ve got the createPost method in the component.

This method checks if the title exists. If it does, it tells the PostService to execute the POST request.

If the request is executed successfully, it adds the new post in the first position (we did this so you could see the result of the post request easily at the top).

The addPost method configures the headers and executes the POST request.

The second argument passed to Angular’s http client is the data of the POST request and the final argument is the RequestOptions which has our Header as well.

As simple as that!

We aren’t going to add the PUT and DELETE requests in the sample code. That’s some homework for you. But we will help you get there/

PUT Request

Here’s what a PUT request would look like.

The only difference is that we change the method to http.put and add the id at the end of the URL to hit the RESTful API.

DELETE Request

All you need to do here is change the method to http.delete and pass the id at the end of the URL to hit the RESTful API.

Here’s an interesting exercise for you to try. Try deleting the POST as soon as the user hits delete and adding it back with an error message (in the catch operator) if the delete fails.

Preventing CSRF Attacks

As per Open Web Application Security Project (OWASP), CSRF ranks right up there with XSS and SQL Injection. It’s not a vulnerability you want to overlook.

What is CSRF?

Let’s say you log in to your online banking account. You take care of some transactions and right when you’re about to log out, your friend sends you a message –

“Dude! This new website is sick…. You have to check it out –”

You’re fingers take the click bait and you click on the website that opens up in a new tab on the same browser. You innocently look at the cat sitting on a dog and saying “I love you”.

You decide to submit a funny comment. And you click submit.

BEEP BEEP! (your phone)

Thank you for your payment of $2,000.00 to Fred BigLol. Have a great day!

Cross Site Request Forgery occurs when a malicious website submits a form to another website. The other website doesn’t recognize the origin and processes that form.

In the example above, the hacker added a hidden form that was “filled out” in advance and submitted when the user submitted his comment.

The good news is that the other server does not have access to the cookies from any other domain (because browsers scope cookies by domain). The bad news is that it doesn’t matter.

When the hacker submits the request, he submits the form to the banking website. So the browser innocently sends cookies associated with that website in the form. Your bank authenticates based on the cookie and BOOM! It’s over.

Preventing CSRF Attacks

To prevent CSRF attacks, the client and the server need to work together.

The Angular team has made this job easier for you (of course) by taking care of the client side. It applies a default CookieXSRFStrategy to all requests.

A common way to deal with XSRF is to send a randomly generated authentication token along with a header for the server to validate that the request has originated from the correct source.

The CookieXSRFStrategy takes care of adding the cookie and the header. It’s the server’s job to compare the cookie and the header and process the request only if they match.

The reason this works is because cannot add anything to the header of your app. Only your app can do that. So the server knows that the request has generated from an untrusted source.


In this article, you’ve learned everything you need to go out and implement Angular’s Http client in your app. You even brushed up on your RxJS skills along the way.

We love your feedback, questions, and comments so fire away! Tell us what you want to read about next!

And as always console.log('Happy Coding!').