AngularJS–Part 4, Accessing server side resources

Introduction

This is a series of posts to describe our approach to slowly migrate a Silverlight based client of a huge and complex LOB  to an HTML5/CSS3/JavaScript based client. These posts report on the lessons learnt and are meant to be used as a reference for our development teams. The first few post can be found here

As mentioned above, this is about migrating a Silverlight based client of a LOB application and consequently we can assume that most if not all of the server side resources will be reused by the new client. How can we access all these resources in an easy and straight forward manner?

Background

To communicate between our Silverlight client and the server we have been using a WCF service with custom binary serialization. For a developer this communication was completely transparent; a message is sent and an asynchronous response is obtained. All the “ugliness” of the communication was hidden behind a custom built framework. Although this kind of client server communication offered certain advantages it was a real pain when it came down to monitor and analyze the network traffic. As stated messages transported over the wire were not human readable since they were binary serialized. Well known tools like Fiddler or the now very powerful browser developer tools are near to useless in these scenarios.

Also the whole communication infrastructure is way to heavy weight for what we are needing it. Sometimes it seems like killing a mosquito with a cannon. Our goal is to use a much leaner method of accessing resources. In this regard a REST API looks promising. It is not my intent to discuss the pros and cons of a REST API versus other methods in this series of posts. Let’s just assume that we did our homework and move on.

AngularJS offers different built-in ways of communicating with a server. The service we want to discuss here is the so called $http service. It provides us an easy and elegant way to communicate via HTTP protocol with a web server. We get the $http service in a controller via dependency injection.

A sample

Let’s add a new HTML file to our sample and call it step4.html. We start with the usual setup which includes defining header and body and referencing the css and JavaScript files. We will also add a new JavaScript file called step4.js to our sample. Thus we have

image

I have added the ng-app directive to the body tag referencing an application called step4App. I have also added a div marking a region of the view which will be managed by the controller FriendsCtrl.

The content of the JavaScript file looks like this

image 

First we define our Angular app called step4App, then we define a FriendsCtrl controller. Currently the controller is just an empty hull but we will soon enrich it with functionality.

Note that I’m using Visual Studio 2013 to edit my HTML and JavaScript files. The first line in the above code snippet shows the way how in Visual Studio we can have intellisense working for any JavaScript file. In this case we get intellisense for all Angular features. One could say that this statement corresponds somehow to the using statements in C#.

Now lets add a button to the view that when clicked loads a list of friends from the server using the $http service. Thus add this to  the div

image

and then define the function wired to the button click event in the controller

image

Ok, I agree, this is quite a bit of new stuff here. Let’s discuss each piece in turn. First of all we inject the $scope and the $http service into our FriendsCtrl controller. The $scope we have already discussed in previous posts and the $http service we will discuss in detail in this post. Suffice to say for now that we need the $http service to communicate with the server.

On the $scope we define the loadFriends function. This function uses the $http service and its get helper function to access a resource located at the (relative) URL api/friends .

In my case api/friends represents a resource provided by a ASP.NET Web API controller called FriendsController. Since this is a series about AngularJS I do not intend to go into details about how to create a RESTful API using ASP.NET Web API.

The $http.get function creates and HTTP GET request to the respective URL and accepts a response that is JSON formatted.

Since all communication over the HTTP protocol is asynchronous the $http.get method is a non-blocking method call and returns a promise. JavaScript promises are a very important concept and we will discuss promises in more detail in a future post.

With this promise returned by the $http.get function we can register two callback functions that are executed once the call has either succeeded or failed. In our case I register this function for the success case

image

In the above function I just take the data that comes from the server and which is encoded as JSON and assign it to the friends variable on the $scope. We will see shortly what we can do with the $scope.friends model in the view.

I also register this function for the case that the call fails (errors)

image

The above function just alerts the user that something terrible has happened.

If I use Chrome and open the developers tools (Shift-Ctrl-J) I can analyze how the answer of my HTTP GET request looks like

image

As you can see, the data is indeed JSON encoded and we get an array of objects each having a FirstName and LastName property.

The ng-repeat directive

Now that we can retrieve data from a (web) server we want to display it in our view. As we have seen above, our $http call returns an array of (friend) objects. Lets display this list as an unordered list. Angular offers us a very powerful directive called ng-repeat that we can use whenever we have to deal with list type data. Let’s use this new directive. Immediately after the button we add the following snippet

image

As I said, we display our friends model as an unordered list. We use the ng-repeat directive to create as many list items (<li> tags) as we have items in the friends collection. The expression “friend in friends” can be compared with a foreach loop in C#. We use the mustache syntax described in my first post to display the full name of the friends. If we run the application the result looks like this

image

If we’d rather display the list of friends as a table then we can do so

image

again we have used the ng-repeat directive to create as many table rows as there are items in the friends collection.

Success versus Error

How do I know when the success function and when the error function is called? AngularJS calls the success function whenever the status code returned in the response header is in the range 200-299 other wise it calls the error function. There is one exception though, if the status code indicates a redirection (3xx) then the HTTP request will (transparently) follow it instead of calling the error function.

Summary

In this post I have shown how we can use the $http service provided by AngularJS via dependency injection to retrieve data from a (web) server. The $http service makes it very easy to create asynchronous HTTP GET requests and subsequently handle the response. I also have introduced the ng-repeat directive which can be used to display list type data. This directive is one of the most powerful directives Angular offers.

In the next post I will discuss how we can use the $http service to send data back to the server.

Related Articles:

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

About Gabriel Schenker

Gabriel N. Schenker started his career as a physicist. Following his passion and interest in stars and the universe he chose to write his Ph.D. thesis in astrophysics. Soon after this he dedicated all his time to his second passion, writing and architecting software. Gabriel has since been working for over 12 years as an independent consultant, trainer, and mentor mainly on the .NET platform. He is currently working as chief software architect in a mid-size US company based in Austin TX providing software and services to the pharmaceutical industry as well as to many well-known hospitals and universities throughout the US and in many other countries around the world. Gabriel is passionate about software development and tries to make the life of developers easier by providing guidelines and frameworks to reduce friction in the software development process. Gabriel is married and father of four children and during his spare time likes hiking in the mountains, cooking and reading.
This entry was posted in AngularJS, introduction. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • Matt

    Thanks for this series of posts Gabriel, I have found them very useful. It would be great to hear your take on communication patterns in AngularJS as part of this series. I have found deciding on a clean way of communication between services and controllers and between controllers to be somewhat confusing.

  • Sam Barnum

    Thoughts on providing user feedback while the request is in progress?

    • gabrielschenker

      This is a good question and I probably will discuss this in a later post when I’m addressing “long running” commands.

  • Max

    Great series , thank you very much : )

    “In my case api/friends represents a resource provided by a” … I guess there is no reason to scare people off : suffice to create an api/friends.josn ( or /api/friends.json ) file with some json content …

  • Riko

    I’m finding your posts really helpful and well structured to get the hang of angular, so thank you. However it is quite frustrating that you didn’t provide any help with the Web API bit. I’m following along in Visual Studio and now I’m completely stuck – I can’t continue because I don’t know how to create a web API method that will return the data. Would it have been that bad to just have a two-line instruction, or even a pointer somewhere else on how to do that?

    • gabrielschenker

      I’ll publish a post shortly about how to provide a simple RESTful api on the server which can be consumed by the AngularJS application.

      • Riko

        Thank you very much!

        • Riko

          Aah, I should have just read ahead to the next step, it’s all shown there, as well as a link to code on GitHub provided! Apologies…

  • LG Optimusv

    After reading the $http.get, I expect a section about $resource for the get method and then $http.post and of course $resource for $http.post too.

    Sorry for my bad written English. Hope you understand what I meant.

  • Matt Frear

    Would be nice to show additionally how to load the list of friends when the page loads, as well as when the user clicks the button. You probably show that in an upcoming post I haven’t read yet :-)

  • mauro

    hi gabriel, i have a problem with the errors, when i write
    error(status){
    alert(status);
    }
    it reponds 404, but in the console log i receive a 500 staatus code, how can i take the second status as a response?

  • Andy Philips

    Gabriel, thanks for all of these great posts, hard work and attention to detail you’ve placed in here. I’m learning a lot of new information and having fun while I do it. It’s great to play with these programs. A word of advice to anyone reading down here, if you have a simple http server set up and don’t want to bother yet with active content or RESTful APIs, just create a static JSON file (friends.json) and let the web server serve that page. For this Part 4, I’m using node’s http-server (npm install http-server) which only serves static content and created a file with the following data:
    [ {"FirstName": "Bob", "LastName":"Smith"},
    {"FirstName": "Jane", "LastName":"Doe"},
    ...]