Using Angular Js $http from custom Service

Well before going in to this tutorial I am assuming you are using brackets to run these sample applications. The reason I am asking is because brackets has an inbuilt webserver which runs our app from the localhost like below


I run my application by clicking the preview icon from brackets so which will dynamically deploy my app contents in its inbuilt server and assign a random available port and in this case 58586 is my port you may end up getting a different port as brackets assigns its random ports form a range which is defined in one of its configuration files.

Now we are going to make our own json service and run it form our browser first. Let’s create a new folder called data under js and a new file carDetails.json inside the data folder.


{     cars:[                {url:"",                 name:"SHELBY",                 desc:"The Shelby Mustang is a high performance variant of the Ford Mustang which was built by Shelby from 1965 to 1968, and from 1969 to 1970 by Ford. Following the introduction of the fifth generation Ford Mustang in 2005, the Shelby nameplate was revived as a new high-performance model, this time designed and built by Ford.[1]"},                {url:"",                 name:"BMW",                 desc:"BMW was established as a business entity following a restructuring of the Rapp Motorenwerke aircraft manufacturing firm in 1917. After the end of World War I in 1918, BMW was forced to cease aircraft-engine production by the terms of the Versailles Armistice Treaty.[5] The company consequently shifted to motorcycle production as the restrictions of the treaty started to be lifted in 1923,[6] followed by automobiles in 1928â29"},                {url:"",                 name:"LANDROVER",                desc:"Land Rover is a car brand that specialises in four-wheel-drive vehicles, owned by British multinational car manufacturer Jaguar Land Rover, which is in turn owned by India's Tata Motors since 2008.[4] The Land Rover is regarded as a British icon, and was granted a Royal Warrant by King George VI in 1951"}               ] }

We have simply copied the contents from our service and put it inside this json file and lets assume that this json service is coming from our server. To test this service you can hit the below url in your browser

Here is nothing but your localhost you can very replace this with your IP Address or localhost. Now you will be seeing this in your browser

Cool now you have created your own service and this just like any other service, which comes from the server. Now let’s see how we are going to use this service.

Go to you carService.js and do the following steps.

app.service('carService',function($http){     var cars;          function getCarDetails(){         return cars;     }          function requestCarDetails(callbackFn){         $http.get('/js/data/carDetails.json').then(function(response){             cars =;             callbackFn(;         });     }    return{        requestCarDetails:requestCarDetails,        getCarDetails:getCarDetails    }  });

In the above code I have introduced a new API called requestCarDetails which accepts a callback function and that call back function gets executed once the carDetails.json gets loaded with successful response. Well to understand this callback better let’s look at the code in our controller.


app.controller('mainController',function($scope,carService){      $ = carService.requestCarDetails(function(cars){          $ = cars;          $scope.desc = $[0].desc;      });          $scope.onSelect = function(index){        $scope.desc= $[index].desc;     } });

If you closely look at the above code, I am priming cars in $scope by calling requestCarDetails with a call back function as a parameter and when the carDetails.json service gets loaded in carService this call back function will be executed and the control comes here with cars as the response. Then this cars is set to $ and also default first time desc is set inside the same callback function. Cool after introducing the json service the same code will get executed without change in any output except the fact that now we are retrieving the cars array from the json service from our webservice.

Some bonus here…

Why is the requestCarDetails retrun cars instead of getting callback as a function and executing the callback function on success response?

The reason behind is “ASYNCHRONOUS”, well because of JS async nature when we try to return a service call the control will go to the next line and in that line if we are using $ it will be undefined so an error may throw at the console stopping the whole execution. This is one way of dealing with async stuffs but I am sure the most optimal and better way is to use promises and $q service from angular. We will see this better stuffs in a different tutorial.

Download Demo


Leave a Reply

Your email address will not be published. Required fields are marked *