<!DOCTYPE html>
<html ng-app="myapp">
<head>
<script data-require="angular.js@1.0.8" data-semver="1.0.8" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="MainController">
<div ng-show="!name">Loading user...</div>
<div ng-show="name">Hello, {{name}}!</div>
</body>
</html>
(function() {
function UserServiceFactory(HttpService) {
return {
getUser: function() {
return HttpService.get('user.json').then(function(response) {
return response.data.user;
});
}
};
}
function HttpServiceFactory($q, $http) {
function doRequest(method, url, data, config) {
var request = angular.extend({}, config || {}, {
method: method,
url: url,
data: data || null
});
return $http(request).then(function(response) {
var data = response.data;
if (data.isError) {
// rejects the request (response.isError is a flag)
return $q.reject(data);
} else {
return data;
}
},
function(errorResponse) {
// rejects the request
return $q.reject(errorResponse);
});
}
return {
// method for GET requests
// the other methods were implemented too
get: function(url, config) {
return doRequest('GET', url, null, config);
}
};
}
function MainController($scope, UserService) {
$scope.name = '';
UserService.getUser().then(function(user) {
$scope.name = user.name;
});
}
angular.module('myapp', [])
.service('HttpService', ['$q', '$http', HttpServiceFactory])
.service('UserService', ['HttpService', UserServiceFactory])
.controller('MainController', ['$scope', 'UserService', MainController]);
}.call(this));
# AngularJS + HttpService
Example code for this answer:
http://stackoverflow.com/questions/18860591/how-to-write-services-with-q-and-http-calls-without-being-repetitive
{
"isError": false,
"data": {
"user": {
"name": "John Doe"
}
}
}