What is Angularjs service ?

AngularJS supports the concepts of “Separation of Concerns” using services architecture. Services are javascript functions and are responsible to do a specific tasks only. This makes them an individual entity which is maintainable and testable. Controllers, filters can call them as on requirement basis. Services are normally injected using dependency injection mechanism of AngularJS.

AngularJS provides many inbuilt services for example, $https:, $route, $window, $location etc. Each service is responsible for a specific task for example, $https: is used to make ajax call to get the server data. $route is used to define the routing information and so on. Inbuilt services are always prefixed with $ symbol.

If I define service in short, its just a helper function which will use entire code. its single tone class with call only once. means service object created only single time after that object will be used.

I’d like to share service basic example

Using service method

Using service method, we define a service and then assign method to it. We’ve also injected an already available service to it.

mainApp.service('CalcService', function(MathService){ this.square = function(a) { return MathService.multiply(a,a); } }); 

its pretty simple mainApp is your module name and you just need to add service using .service. but as per guild line it not recommended way. so let have look of style guide  service

(function(){ 'use strict' angular .module('mainApp') .service('MyService', MyService); MyService.$inject = []; function MyService(){ var self = this; self.userData = {}; self.getShareData = getShareData; function getShareData(){ return self.userData; } } })() 

In above example I’ve created a service called ‘MyService’ which have a getShareData method which returns userData.

Leave a comment

Start a Blog at WordPress.com.

Up ↑

Design a site like this with WordPress.com
Get started