Sunday, March 2, 2014

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 calledstep4App. 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 FriendsCtrlcontroller. 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 $httpservice to communicate with the server.
On the $scope we define the loadFriends function. This function uses the $httpservice and its get helper function to access a resource located at the (relative) URLapi/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.getmethod is a non-blocking method call and returns a promiseJavaScript 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-repeatdirective to create as many list items (
  •  tags) as we have items in the friends collection. The expression “friend in friends” can be compared with aforeach 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.

    4 comments:

    for ict 99 said...

    AngularJS is an incredible tool Angularjs Online Training development tricks and methods AngularJS Interview Questions AngularJS application Angularjs Training in Chennai Data Binding Angular.js Course Root Scope and Extending Scope Angularjs Training

    oakleyses said...

    lululemon canada, nike air max, burberry outlet, oakley pas cher, burberry handbags, coach outlet store online, kate spade, michael kors outlet, michael kors, nike air force, true religion jeans, true religion outlet, michael kors, polo lacoste, nike tn, new balance, abercrombie and fitch uk, michael kors outlet, uggs outlet, michael kors outlet, ralph lauren uk, michael kors outlet online, replica handbags, coach outlet, true religion outlet, coach purses, nike free uk, sac vanessa bruno, mulberry uk, michael kors outlet online, michael kors outlet online, michael kors outlet online, north face, uggs outlet, converse pas cher, hogan outlet, nike air max uk, hollister pas cher, sac hermes, nike roshe run uk, hollister uk, nike air max uk, true religion outlet, timberland pas cher, vans pas cher, ray ban pas cher, guess pas cher, ray ban uk

    oakleyses said...

    ipad cases, beats by dre, iphone 6 cases, ferragamo shoes, wedding dresses, hollister clothing, p90x workout, instyler, asics running shoes, nike huaraches, hermes belt, north face outlet, s6 case, babyliss, nfl jerseys, hollister, iphone 6 plus cases, insanity workout, ralph lauren, iphone cases, iphone 6s plus cases, bottega veneta, new balance shoes, longchamp uk, iphone 6s cases, giuseppe zanotti outlet, nike roshe run, mont blanc pens, herve leger, oakley, lululemon, timberland boots, nike air max, iphone 5s cases, ghd hair, valentino shoes, louboutin, nike trainers uk, celine handbags, north face outlet, baseball bats, vans outlet, abercrombie and fitch, chi flat iron, soccer jerseys, mac cosmetics, mcm handbags, soccer shoes, jimmy choo outlet, reebok outlet

    oakleyses said...

    supra shoes, marc jacobs, canada goose, converse outlet, toms shoes, ugg uk, ugg pas cher, canada goose outlet, canada goose, nike air max, louis vuitton, karen millen uk, doudoune moncler, converse, louis vuitton, vans, gucci, montre pas cher, moncler outlet, canada goose uk, canada goose outlet, moncler, pandora jewelry, barbour uk, moncler outlet, juicy couture outlet, louis vuitton, canada goose, pandora uk, coach outlet, swarovski crystal, ugg,uggs,uggs canada, juicy couture outlet, links of london, louis vuitton, louis vuitton, hollister, swarovski, canada goose outlet, ray ban, moncler, ugg, barbour, ugg,ugg australia,ugg italia, replica watches, pandora charms, moncler uk, pandora jewelry, wedding dresses, canada goose jackets, hollister, lancel