The most common and flexible way to create a service uses the angular.module API factory:
angular.module('myApp.services', []).factory('githubService', function() {
var serviceInstance = {};
// Our first service
return serviceInstance;
});
The service factory function can be either a function or an array, just like the way we create controllers:
// Creating the factory through using the
// bracket notation
angular.module('myApp.services', [])
.factory('githubService', [function($http) {
}]);
To expose a method on our service, we can place it as an attribute on the service object.
angular.module('myApp.services', [])
.factory('githubService', function($http) {
var githubUrl = 'https://api.github.com';
var runUserRequest = function(username, path) {
// Return the promise from the $http service
// that calls the Github API using JSONP
return $http({
method: 'JSONP',
url: githubUrl + '/users/' +
username + '/' +
path + '?callback=JSON_CALLBACK'
});
}
// Return the service object with a single function
// events
return {
events: function(username) {
return runUserRequest(username, 'events');
}
};