The role services play in an Angular application is clear, but there can be confusion around the creation of services. This is because there are three very similar ways to create a service in Angular. We will look at each of these and why they should be used.
A service in Angular is an object that can be an authority on data (meaning it is the only source of some data). A great example is the route provider as it is the only object that provides route information. It is a singleton that all modules utilize, a way to keep data in sync between controllers, or all of these! A great example of a service that you will most likely need is $http
. It makes AJAX requests for you. You can build a service that returns data from your API and you do not have to worry about creating AJAX calls in each and every controller.
Another example is the $route
and $routeParams
services. When you have a reference to the $route
service, you can always find out what route has been matched. The $routeParams
service will let you know the parameters.
Services should be used anytime you have the need to write the same code more than once. You can pull it out and put it into a service. In addition to this, services should be created for any data that will be used by more than one controller. The controller can then ask the service for the data. This will keep this data the same across multiple controllers.
All of the functions listed can be called from the module or off the $provide
injectable object.
Factory, service, and provider will all rely on an HTML template of this:
<div ng-controller="SimpleController"> {{ service }} </div>
This is the method to create factories:
module.factory(name, getFunction)
The service factory is great when you need a singleton. No configuration other than what is done in the factory()
function is done. The object will be the same each time it is injected.
Here is a simple example that will return the name of the service. The example also creates a dependency on $http
:
firstModule.factory('firstFactory', ['$http', function ($http) { var serviceName = 'firstFactory'; return { getName: function(){return serviceName;} }; }]);
Services can be initialized with new
keyword:
module.service(name, constructor)
The key distinction between a service and a factory is that it can be initialized with new
. Here is an example that depends on $http
:
firstModule.service('firstService', ['$http', function ($http) { return function (name) { var serviceName = name; this.getName = function () { return serviceName; }; }; }]);
Here is the controller that will initialize the service:
firstModule.controller('SimpleController', ['$scope', 'firstService', function ($scope, firstService) { var first = new firstService('First Service Name'); var second = new firstService('Second Service Name'); $scope.service = second.getName(); }]);
The function that provides the most control of the setup of a provider:
module.provider(name, provider)
This is the final and most complex way to build a service. It must return an object with a $get
method. You should use this when you must have this object ready for configuration. This is the only provider that can be injected during the configuration phase of application startup. The word "provider" will be appended to the name of this. For example, if you named your provider my
, it will be injected using myProvider
. Here is an example provider that has its name injected during configuration. First up is the provider definition:
firstModule.provider('first', function () { var serviceName; return { configSet: function (name) { serviceName = name; }, $get: function () { return { getName: function () { return serviceName; } }; } } });
Next is the configuration. Notice how it is injected using firstProvider
:
firstModule.config(['firstProvider', function (firstProvider) { firstProvider.configSet('firstProvider123'); }]);
Finally, here is the controller:
firstModule.controller('SimpleController', ['$scope', 'first', function ($scope, firstProvider) { $scope.test = firstProvider.getName(); }]);
This is the service used to make HTTP calls:
$http(config)
config(object)
: This object has the following properties:method(string)
: This is the HTTP method.url(string)
: This is the URL.params(string or object)
: This is the params for the request. An object will be mapped key to value for this.data(string or object)
: This is the data to be sent in the request.headers(object)
: This sets the headers for the request.xsrfHeadername(string)
: This is the name of the header for XSRF.xsrfCookieName(string)
: This is the name of the cookie for XSRF.cache(Boolean)
: This is used to decide whether to cache data or not.responseType(string)
: This is used to decide what the request type will be.You can use all of the HTTP methods as functions: GET
, POST
, HEAD
, PUT
, DELETE
, and PATCH
. We will just look at GET
, POST
, and JSONP
closely.
GET
, POST
, and JSONP
will cover most, if not all, of many people's needs for $http
. If this does not, view the $http
documentation at https://docs.angularjs.org/api/ng/service/$http.
Each function will take the URL as the first parameter and a config
object, which is the same config
object that $http()
gets.
$http.get(url, config)
This executes a simple GET
request. Here is an example of a factory that uses $http.get
:
firstModule.factory('httpService', ['$http', function ($http) { return { test: function () { return $http.get('test', {params: 'test'}); } } }]);
This returns a promise that the controller can then use:
firstModule.controller('SimpleController', ['$scope', 'httpService', function ($scope, httpService) { httpService.test().success(function (data, status) { console.log(data); }) .error(function (data, status) { console.log('An error occured');}); }]);
$http.post(url, config)
This will make a POST
request. Here is a factory that makes a POST
and an example that uses localhost. Remember that you must be running a server that responds to POST
requests for this to work:
firstModule.factory('httpService', ['$http', function ($http) { return { test: function () { return $http.post('http://localhost/post', { data: 'HEY' }); } } }]);
I will list out some useful services that can be injected, with a short blurb about each:
$anchorScroll
: This parameter allows you to scroll to the element in the hash$animate
: This parameter allows DOM manipulations$cacheFactory
: This allows caching$http
: See $http
$interval
: This uses Angular's way to call setInterval
$location
: This gets the information about window.location
$rootScope
: This returns the root scope for the application$route
: See Routing
$q
: This allows promises to be added in our project$timeout
: This uses Angular's way to call setTimout
This is not a comprehensive list as Angular has many services and can create and include more. These are the ones that you will most likely use in your applications.
18.222.93.132