AngularJS and $httpBackend

I was helping out someone with their first attempt at an AngularJS website and they sent me the html and javascript file. The problem was that they used a web service to which I don’t have access so I needed a way to simulate that web service. I thought about writing my own version of the MVC web service but that seemed like overkill for what should just be a quick project. What I did find was $httpBackend which you can use to mock $http call with, the documentation for $httpBackend is here

The code is also on JSFiddle

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
//You need to inject the ngMockE2E module into your application's module
var myModule = angular.module('myModule', [ 'ngMockE2E']);
 
//Adding a global variable that can be injected into controllers and services
myModule.value('globalBaseUri', '/myService');
 
myModule.run(['$httpBackend', 'globalBaseUri', function($httpBackend,globalBaseUri) {
 
	//I wrapped the data to mimic how the Service is returning the data
    function wrapReturn(data) {
        var returnData = {};
        returnData.d = data;
        return returnData;
    }
 
    var responseData = [{keyword: 'countryname' , color: "red"}, 
                        {keyword: 'portofregistry', color: "orange"}, 
                        {keyword: 'placename', color: "orange"}, 
                        {keyword: 'flag', color: "orange"},
                        {keyword: 'field', color: "green"}],
        baseUri = globalBaseUri + "/getData";
 
	//when there is a $http call to '/myService/getData' I want the the responseData to be sent instead of 
	//Angular trying to connect to the non-existent web service
    $httpBackend.whenPOST(baseUri).respond(wrapReturn(responseData));
}]);
 
myModule.factory('myService', ['$http', 'globalBaseUri', function ($http, globalBaseUri) { 
 
    var _self = this;
 
	_self.data = {};
	_self.data.serverData = [];
 
	function loadServerData(baseUri, paramValues, onSuccess) {
		$http.post(baseUri, paramValues).success(function (data) {
            if (onSuccess) {
                var vessels = data.d;
                onSuccess(vessels);
            }
        });
	}
 
	function init(paramValue) {
 
		loadServerData(
			globalBaseUri + "/getData", 
			{ param1 : paramValue }, 
			function (data) {
				_self.data.serverData = data;
			}
		);
	}
 
	return  {
		data : _self.data,
		init: init
	};
}]);
 
 
myModule.controller('myController', ['$location', 'myService', function ($location, myService) {
 
	var _self = this,
        token =  $location.search().Token;    
 
    myService.init(token);
	_self.data = myService.data;
}]);

One thought on “AngularJS and $httpBackend