Starting with Angular part 3 – services

We have covered basic topics in the first two tutorials. Now it is time to see something a little more advanced. In this tutorial we will see how to add services to our application, after all there is no application without some sort of data coming from somewhere.

Wouldn’t it be nice if we could figure out not only how to retrieve data, but also how to separate this functionality into something a little more advanced like a factory ?

Let’s see how we can do this. So, we will build a simple application which reads some data from an external URL and when that data is loaded it does a little processing.

Let’s start with a simple Html page :


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script src="app.js"></script>
<script src="dataFactory.js"></script>
</head>
<body ng-app="tutorial3App">
<div id="content" ng-controller="tutorial3Controller">
<div ng-repeat="item in tutorialData">
{{item}}
</div>
</div>
</body>
</html>

What’s going on here ? We can see the usual ng-app and ng-controller and a little loop to repeat some data. We should be familiar with this from the first two parts of this series. If you need a little reminder ( no shame in that ! ),  at the bottom of this page I have included links to the previous articles.

So nothing fancy here, but notice we have two JavaScript references this time.

Let’s look at the app.js file :


(function () {
angular.module('tutorial3App', []);

angular.module(‘tutorial3App’).controller(‘tutorial3Controller’, [‘$scope’, ‘$http’, ‘dataFactory’, function ($scope, $http, dataFactory) {
$scope.tutorialData = [];

$scope.processTutorialData = function()
{
$scope.tutorialData.push(‘local data’);
}

$scope.init = function () {
dataFactory.getMeTestData().then(function (data) {
$scope.tutorialData = data;
$scope.processTutorialData();
})
}

$scope.init();
}]);
})();

Ok, there are some differences this time so let’s have a look see if we can figure out what’s going on here.

First of all, we can see we’re injecting an $http object into our controller. What is $http ? Well, it is a core Angular service and the documentation tells us that it facilitates communication with the remote HTTP servers via the browser’s XMLHttpRequest object or via JSONP.

You can read more about it here : Angular $http service documentation

We will need this service to fire a call for our data. Next, we can see we inject a new thing called dataFactory. Ok this is definitely new and it must be coming from somewhere right? Yes, you are 100% right, but for now let’s keep looking at the rest of the app.js file.

We can see some boring properties and methods, however there is one interesting thing,  an init method which we call at the bottom of the code.

This method references the dataFactory again and then it does some fancy stuff. At this point we’re ready to look at the second JavaScript reference and see what’s in it :


angular.module('tutorial3App').factory('dataFactory', function ($http, $q) {
var service = {};

service.data = [];

service.getMeTestData = function () {
return $http.get(‘someUrl’).then(function (response) {
service.data = response;
return service.data;
})
}

return service;
});

We are now looking at a little more advanced Angular, but it shouldn’t be too scary. So, first of all we inject dataFactory into our application module using the factory function. Inside this factory we create a service JSON object and then we assign a property and a method to it. The getMeTestData method fires a $http.get request. if you read the documentation it will tell you that $http.get returns a promise. 

Hang on a sec that sounds fancy, what exactly is a promise ? Think of an async request, you fire a request and at some point it will complete and return the data. A promise is just that, a promise that at some point we will get some data. When the data is available whatever is inside the when function will execute.

In our case, we will take the data which comes back, assign it to our internal property service.data and then we will return it. This is all that happens inside this fancy dataFactory. I bet you now think that actually, it doesn’t feel fancy at all and you would be right.

One last thing we didn’t explain is $q, what exactly is that ? Again we will search the angular documentation and find out that it is a service that helps you run functions asynchronously, and use their return values (or exceptions) when they are done processing. More details here

So at this point, hopefully everything is clear and we can look at the app.js file again, specifically at the $scope.init method. We can now see that it calls our data factory using the name we injected earlier, it calls the getMeTestData which of course return a promise so we wait until it completes by calling the when function and in there we assign this data to a local property and then we do some processing to it. In our case it simply returns an array of items and we inject one more once we receive it. The important thing here is that we need the data call to complete and then we do something with it, which is a common scenario in any application.

This should give you an understanding in how we build a real application with Angular and how simple things really are.
I have provided a little service consumed by this tutorial just to show a real call in action.

This is what you see when you run the application :

angulartutorial3result

The first 2 items are coming from our service call, the third was added locally after the data was received.

Please note that the service which delivers the data for this tutorial is  NOT guaranteed to be always up. If you happen to get an error when running the application, feel free to replace it with a call to a service under your control. all you have to do is return an array of items like this :

["item 1 from service","item 2 from service"]

I hope you enjoyed this mini series this far. In the next chapter we will look into how to build a more serious application.

If you’d like to download the code for this tutorial, you can do it here : Angular Tutorial Part 3 – services

As usual, the code is released under the MIT License

Have fun and see you later !

Starting with Angular

Starting with Angular Part 2 – loops

Advertisements

About eidand

Senior Dot Net developer specialised in C# / Sql Server / Mvc / Wcf
This entry was posted in Code and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s