http

Often, I find people asking the question about how to properly use promises and http factories, to retrieve data from a web service in AngularJs. I want to share the way I’ve adapted to using factories, which has streamlined the way I use them throughout my applications.

As you know, $http supports promise chaining, which allows me to write my factory like so:

(function(){
	'use strict';
	
	angular
		.module("DemoApp")
		.factory("DemoFactory", DemoFactory);
	
	// Dependency Injection	
	DemoFactory.$inject = ['$http'];
	
	function DemoFactory($http) {
		return {
			getData: getData
		};
		
		// Endpoint
		var uri = "http://somedomain.com/api";
		
		// Function to get data
		function getData() {
			$http.get(uri + "/GetData")
				.then(getDataComplete)
				.catch(getDataFailed);
			
			// Webcall was successful
			function getDataComplete(response) {
				// Return the response data
				return response.data;
			};
			
			// Webcall failed
			function getDataFailed(error) {
				// Log the error (for lack of better error handling)
				console.log("Error retrieving data: " + error.message);	
			};
		};
	};
		
})();

As you can see, I’m now able to easily handle the response, and catch error messages from the web service.

In my controller, it’s now dead simple to request data from the service:

(function(){
	'use strict';
	
	angular
		.module("DemoApp")
		.controller("DemoCtrl", DemoCtrl);
	
	// Injecting our factory here
	DemoCtrl.$inject = ['DemoFactory'];
		
	function DemoCtrl(DemoFactory) {
		var vm = this;
		vm.data = {};
		
		// Function that runs when the ctrl is called
		function activate() {
			getSomeData().then(function(data){
				// Binds data to view model
				vm.data = data;
			});
		};
		
		// Function to get the data
		function getSomeData() {
			return DemoFactory.getData()
				.then(function(data){
					// Returns the data from the factory
					return data;
				});	
		};
	};
})();

Hopefully these code snippets will help you with your service calls, please let me know in the comments below, if you have any questions. I would be happy to answer them the best that I can!

Leave a Reply

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