This article will demonstrate built-in AngularJS Services as well as how you can create your own custom service in an AngularJS. This article begins with a brief introduction to AngularJS Services. Afterwards, it demonstrates built-in AngularJS Service with syntax and links to an example on Plunker Editor. Finally, the article discusses custom AngularJS Services.
AngularJS ServicesAngularJS Services are re-usable components or the objects, which have the methods and the properties to perform some business logic and can be used throughout your Application. To use an AngularJS Service in controller, filter, Service and Directive; just add it as a dependency. Angular comes with some built-in Services but you can create your own custom Service as well.
Built-in AngularJS Service
AngularJS built-in services always start with a $ sign. Some of the commonly used built-in Services are shown below.
- $http
- $resource
- $q
- $anchorSrcoll
- $cacheFactory
- $locale
- $timeout
- $cookies
- $routeProvider
- $routeParams
- $log
This Service is used to communicate with the Servers over the network; i.e., you can send raw requests like getting and posting the data etc., and to recieve the resposne from the remote Server through this Service.
Syntax
- var app=angular.module('app',[]);
- app.controller('mycontroller',['$http',function($http){
- //$http get method
- $http({
- method: 'GET',
- url: '/someUrl'
- //other properties
- }).then(function successCallback(response) {
- // this callback will be called asynchronously
- // when the response is available
- }, function errorCallback(response) {
- // called asynchronously if an error occurs
- // or server returns response with an error status.
- });
- //$http get shortcut method
- $http.get('/someUrl').then(function successCallback(response) {
- // this callback will be called asynchronously
- // when the response is available
- }, function errorCallback(response) {
- // called asynchronously if an error occurs
- // or server returns response with an error status.
- });
- }]);
$resource
$resource is used for the same purpose as $http Service but the key difference between them is that $resource is based on a RESTful architecture and is used to access Restful Web Services. For using $resource Service, you just need to add Angular-resource script file after AngularJS and dependency of ngResource into Angular module, as shown in the syntax given below.
$resource is used for the same purpose as $http Service but the key difference between them is that $resource is based on a RESTful architecture and is used to access Restful Web Services. For using $resource Service, you just need to add Angular-resource script file after AngularJS and dependency of ngResource into Angular module, as shown in the syntax given below.
- <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.js"></script>//angulrJS file
- <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular-resource.js"></script>//ngresource file
- <script src="your script file"></script>
- var app=angular.module('app',['ngResource']);
- app.controller('mycontroller',['$resource',function($resource){
- //resource get method
- $resource('/someURL').get().$promise.then(function(data){
- //do some stuff
- },function(response){
- //do some stuff
- });
- }]);
$q
$q service is used to handle the promises and the deferred objects. Promises are the pending results of the asynchronous calls and deferred objects returns promises and the results of asychronous operation after its completion to the calling code.
How $q works
Step 1
The client sends asynchronous call to the Service.
Step 2
The Service receives the call and create a deferred object by using $q Service.
Step 3
The deferred object returns the promise to the client.
Step 4
The client uses this promise to write callback functions.
Step 5
The Service performs the work and return the status of the function, which is either successfully completed or rejected through deffered object to the client.
Step 6
The client executes success or an error callback function, which is based on the result return from the Service.
Syntax
Plunker- $q Service Example
$q service is used to handle the promises and the deferred objects. Promises are the pending results of the asynchronous calls and deferred objects returns promises and the results of asychronous operation after its completion to the calling code.
How $q works
Step 1
The client sends asynchronous call to the Service.
Step 2
The Service receives the call and create a deferred object by using $q Service.
Step 3
The deferred object returns the promise to the client.
Step 4
The client uses this promise to write callback functions.
Step 5
The Service performs the work and return the status of the function, which is either successfully completed or rejected through deffered object to the client.
Step 6
The client executes success or an error callback function, which is based on the result return from the Service.
Syntax
- var myApp = angular.module('myApp', []);
- //service create deffered object and return promise
- myApp.service('myService',['$q',function($q) {
- //create a deffered object
- var defferedObject = $q.defer();
- //this method calls when work is being performed
- defferedObject.notify('notification messages');
- //this method calls when something goes wrong
- //and errors send back to the client
- defferedObject.reject('Error Message');
- //this mehod calls when the require
- //work has completed successfuly
- //and results are returned to client
- defferedObject.resolve(data);
- //return promise to caller
- return defferedObject.promise;
- }]);
- myApp.controller('myController',['myService',function(myService){
- //code receive the promise
- //and write callback functions
- //these callback functions receive the result from the service
- myFunction().then(successCallBack, errorCallBack, notificationCallBack);
- function successCallBack(data) {
- //do some stuff with data
- }
- function errorCallBack(error) {
- //do some stuff
- }
- function notificationCallBack(notification) {
- //do some stuff
- }
- }]);
$anchorScroll
$anchorScroll service is used to navigate or scroll within the page.
$anchorScroll service is used to navigate or scroll within the page.
- var myApp=angular.module('myApp', [])
- myApp.controller('ScrollController', ['$scope', '$location', '$anchorScroll',
- function($scope, $location, $anchorScroll) {
- $scope.gotoBottom = function() {
- // set the location.hash to the id of
- // the element you wish to scroll to.
- $location.hash('bottom');
- // call $anchorScroll()
- $anchorScroll();
- };
- }]);
Plunker-$anchorScroll Example
$cacheFactory
$cacheFactory Service is used to cache the data. This Service provides functions through which you can define the capacity of the data objects or the items to be cached, get cache information, put and get the data from cache.
$cacheFactory Service is used to cache the data. This Service provides functions through which you can define the capacity of the data objects or the items to be cached, get cache information, put and get the data from cache.
- var myApp=angular.module('myApp', []);
- myApp.controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
- //Create Cache of capacity(optional) 3
- $scope.cache = $cacheFactory('cacheId',{capacity:3});
- //put data into cache
- $scope.cache.put(key,value);
- //get data from cache
- $scope.cache.get(key);
- //get cache info
- $scope.cache.info();
- }]);
Plunker-$cacheFactory Example

Former memberPosted May 9, 2017, 5:03 AM
Nice article and i have one request that people write article on angular but no one write very h article on angular directive. the angular directive is big area. so would please write few articles on directives part by part.