Sunday, March 2, 2014

AngularJS–Part 4, Accessing server side resources


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?


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
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
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
and then define the function wired to the button click event in the controller
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
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)
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
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
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
    If we’d rather display the list of friends as a table then we can do so
    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.


    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.


    oakleyses said...

    louis vuitton handbags, oakley sunglasses, louboutin, longchamp outlet, nike shoes, louis vuitton outlet stores, chanel handbags, burberry outlet, prada outlet, jordan shoes, tiffany and co, michael kors outlet, tory burch outlet, louis vuitton outlet, longchamp handbags, nike free, true religion jeans, michael kors outlet, kate spade outlet, polo ralph lauren outlet, tiffany and co, prada handbags, polo ralph lauren outlet, michael kors outlet, michael kors outlet, longchamp handbags, oakley sunglasses, ray ban sunglasses, kate spade handbags, burberry outlet, louis vuitton outlet, louboutin outlet, louboutin, coach factory outlet, air max, air max, coach outlet, gucci outlet, christian louboutin shoes, michael kors outlet, coach purses, ray ban sunglasses, michael kors outlet, louis vuitton, coach outlet store online, true religion jeans, oakley sunglasses cheap

    oakleyses said...

    ralph lauren, lululemon, air max, hollister, north face, nike air max, polo lacoste, vanessa bruno, timberland, vans pas cher, louboutin, louis vuitton, oakley pas cher, air max pas cher, nike roshe run, air max, true religion outlet, barbour, sac longchamp, air force, hollister, sac louis vuitton, nike free, polo ralph lauren, nike trainers, louis vuitton uk, nike roshe, sac hermes, longchamp, michael kors, sac burberry, sac guess, mulberry, new balance pas cher, converse pas cher, sac louis vuitton, hogan outlet, nike tn, north face, true religion outlet, ray ban pas cher, michael kors, air jordan, nike blazer, nike free pas cher, michael kors pas cher, abercrombie and fitch, ray ban sunglasses

    oakleyses said...

    mac cosmetics, mont blanc, marc jacobs, canada goose outlet, nike huarache, vans shoes, soccer jerseys, hollister, giuseppe zanotti, beats by dre, abercrombie and fitch, longchamp, insanity workout, celine handbags, bottega veneta, ghd, nfl jerseys, north face outlet, chi flat iron, ugg boots, birkin bag, ugg australia, canada goose, herve leger, ugg pas cher, rolex watches, valentino shoes, canada goose uk, canada goose, ferragamo shoes, canada goose, ugg boots, uggs outlet, north face jackets, soccer shoes, asics running shoes, new balance shoes, p90x, lululemon outlet, canada goose jackets, mcm handbags, instyler, babyliss pro, ugg, wedding dresses, jimmy choo outlet, reebok outlet, nike roshe run

    oakleyses said...

    parajumpers, karen millen, air max, converse, pandora charms, moncler, louboutin, moncler, links of london, lancel, juicy couture outlet, oakley, hollister, pandora charms, supra shoes, thomas sabo, canada goose, gucci, wedding dresses, timberland boots, swarovski crystal, air max, coach outlet store online, moncler, ray ban, canada goose, moncler, ugg, louis vuitton, swarovski, hollister, montre homme, moncler, hollister clothing store, ralph lauren, rolex watches, moncler outlet, moncler, iphone 6 cases, baseball bats, juicy couture outlet, toms shoes, vans, pandora jewelry, ugg, converse shoes

    for IT the 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...

    jordan pas cher, chanel handbags, nike outlet, michael kors pas cher, kate spade outlet, replica watches, longchamp pas cher, nike free, jordan shoes, christian louboutin shoes, nike free run, louis vuitton outlet, oakley sunglasses, ray ban sunglasses, polo ralph lauren, ugg boots, christian louboutin uk, air max, louis vuitton outlet, ugg boots, tiffany jewelry, polo ralph lauren outlet online, burberry pas cher, prada outlet, nike air max, gucci handbags, sac longchamp pas cher, ray ban sunglasses, louboutin pas cher, louis vuitton, uggs on sale, tiffany and co, oakley sunglasses, louis vuitton outlet, ray ban sunglasses, longchamp outlet, louis vuitton, longchamp outlet, replica watches, nike roshe, polo outlet, oakley sunglasses, cheap oakley sunglasses, oakley sunglasses wholesale, christian louboutin, christian louboutin outlet, tory burch outlet

    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