Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use services in Angular?

I am just starting out with Angular. Reading the example of a service in the Google documentation, I just wonder why you would choose to use a service rather keeping the variables and function right in the controller?

angular.
 module('MyServiceModuleDI', []).
 factory('notify', function($window) {
    var msgs = [];
    return function(msg) {
      msgs.push(msg);
      if (msgs.length == 3) {
        $window.alert(msgs.join("\n"));
        msgs = [];
      }
    };
  });

function myController($scope, notify) {
  $scope.callNotify = function(msg) {
    notify(msg);
  };
}

When would you choose to use a service in this case?

like image 837
p0pps Avatar asked May 23 '13 08:05

p0pps


People also ask

What is the use of services in Angular 8?

An Angular service is plain Typescript class having one or more methods (functionality) along with @Injectable decorator. It enables the normal Typescript class to be used as service in Angular application. Here, @Injectable decorator converts a plain Typescript class into Angular service.

Why do we need services?

When customers are happy with the service they receive, they are more likely to trust and be loyal to that company. Good customer service creates a positive experience for customers, which can result in repeat business and referrals. Good customer service is the lifeblood of any business.

What is difference between service and class in Angular?

Any class can be a service. Whether or not it behaves like a service is defined by how you register it. If it is registered in the provider array of a module or component, it is a service. Adding the @Injectable() is only required to tell a service that it needs to inject other services.

What are the types of services in Angular?

There are two types of services in angular: Built-in services – There are approximately 30 built-in services in angular. Custom services – In angular if the user wants to create its own service he/she can do so.


1 Answers

In my opinions the main reasons are:

  • Persist and share data between Controllers.
    I.E: You create a service that fetchs data form a database, if you store it inside a controller, once you change to another Controller the data will be discarded (unless you store it in the $rootScope but this is not the best way to do it) , but if you keep it inside a service (services are singletons), the data will persist when you change controllers.

  • Abstract data access logic by creating an API that will be used by your controllers/directives/services.
    Keep business logic inside Controllers and data logic inside services.

  • DRY (Don't repeat yourself).
    I.E: You have a series of functions that you need in different controllers, without the service you would have to repeat your code in each controller, with a service you can create a single API for this functions and inject it in every Controller/Directive/Service you need.

Here is an example:

var myApp = angular.module('myApp',[]);


//Here is the service Users with its functions and attributes
//You can inject it in any controller, service is a singleton and its data persist between controllers
myApp.factory('Users', function () {

    //data logic
    //fetch data from db and populate...
    var name = "John";
    var surname = "Doe" 

    function getName() { return name; }
    function getFullName() { return name + ' ' + surname; }
    function setName(newName) { name = newName; }

    //API
    return {
        getName: getName,
        getFullName: getFullName,
        setName: setName
    }
});

//An Util service with methods I will use in different controllers   
myApp.factory('Util', function () {

    //a bunch of useful functions I will need everywhere
    function daysInMonth (month,year) {
        return new Date(year, month+1,0).getDate();
    }

    return {
        daysInMonth: daysInMonth    
    };
});   

//Here I am injecting the User and Util services in the controllers   
myApp.controller('MyCtrl1', ['$scope', 'Users', 'Util', function ($scope, Users, Util) {

    $scope.user = Users.getFullName(); //"John Doe";
    Users.setName('Bittle');

    //Using Util service
    $scope.days = Util.daysInMonth(05,2013);
}]);

myApp.controller('MyCtrl2', ['$scope', 'Users', 'Util', function ($scope, Users, Util) {

    $scope.user = Users.getFullName(); //"Bittle Doe"; //The change that took place in MyCtrl1 hhas persisted.

}]);
like image 76
Bertrand Avatar answered Oct 23 '22 05:10

Bertrand