Google+

Friday, August 14, 2015

#10 - What are AngularJS Services and Dependency Injection

In this article we review What are AngularJS Services and Dependency Injection,  by developing an Angular App and using a  built-in AngularJS $service  .
This is the Lesson #10 in the "AngularJS: From 0 To 100" learning articles written for AngularJS  Beginners. This lessons start at Lesson #1  , if you wish to take a look at them.
<<<<  PREVIOUS LESSON                             NEXT LESSON >>>>


We're using the  "Brackets"  open source Editor , which supports AngularJS Apps . You can see the 5 minutes tutorial about Brackets in this post.

Our AngularJS App will be this way :  
What are AngularJS Services and Dependency Injection



What are AngularJS Services and Dependency Injection



$services are singleton (created only once on all the lifespan of the app) objects lazy instantiated (created just the first time the object is needed, not before that) through an entire AngularJS App lifespan (services share variables state, cache and behavior). Using $services we can share state and behavior all over our app. They can be built-in (like $http, $log, $location, $window, etc) , or custom services written by you.
Because of the importance of mastering the AngularJS logging, we'll practice here using the $log AngularJS service. We'll learn about the $http Service while learning to persist data in the web server.
More details about $services can be learned from the official AngularJS web site.
$services implement the Dependency Injection Paradigm,

For example, the traditional way to use a component inside another object is as follows:

function fnUsingAService()
{
     var $someService = new SomeService(new SomeOtherService(new YetAnotherService()));
     $someService.DoSomething();
}

Here we're instantiating a component, which must get some other component instantiated inside. And what if the "SomeOtherService()" also needs some inner services instantiated("YetAnotherService()") ? The component's  chain could be rather complicated.
However, using dependency injection, we don't instantiate neither the injected service, nor the component's chain of services inside it. Instead, we receive it already instantiated and working:

function fnUsingAService($someService)
{     
     $someService.DoSomething();
}

The AngularJS engine takes care of creating the service for us.
Let's see how it works: let's create our own AngularJS and use the $log built in AngularJS Service. First add to the HTML5 the data-ng-app Angular directive, and load the AngularJS Framework via CDN (Content Delivery Network):

What are AngularJS Services and Dependency Injection    1

(copy-paste):

<!doctype html>
<html lang="en"  data-ng-app="usingServices">
<head>  
<meta charset="UTF-8">
  <title>Using Services</title>

  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.7/angular.min.js"></script>
  <script src="Controller.js"></script>
  <link href="style.css" rel="stylesheet"/>
  
</head>


Then add a div bound to a Controller, containing an input text and a button as follows:


What are AngularJS Services and Dependency Injection    2



At the Controller javascript file, create a Controller and use dependency injection inserting two services in it : $scope and $log , as follows:

What are AngularJS Services and Dependency Injection    3



As you see, we are using those two services for the Controller's method: $scope will store the method itself, while $log will be used to output the received message, by calling the $log.info() method.
Browse to the AngularJS app , enter a message and click the button:

What are AngularJS Services and Dependency Injection    4



Then, open the Developer's Tools (F12) to see the "info" message in the Console:

What are AngularJS Services and Dependency Injection   5



Next, append to the AngularJS View another three buttons for sending "warning", "log" and "error" messages through the $log service:


What are AngularJS Services and Dependency Injection 6



(copy-paste):

<body>
  <div data-ng-controller="LogCtl">
  <h2>Type the message to be displayed on the Console:</h2>

  Message:
  <input data-ng-model="msg"/>

  <button data-ng-click='fnShowInfoMessage(msg)'>Info</button>

  <button data-ng-click='fnShowWarningMessage(msg)'>Warning</button>

  <button data-ng-click='fnShowLogMessage(msg)'>Log</button>

  <button data-ng-click='fnShowErrorMessage(msg)'>Error</button>

</div>
</body>
</html>



At the Controller, add the corresponding methods and call the $log warn() , log() and error() functions:

What are AngularJS Services and Dependency Injection    7

(copy-paste):

angular.module('usingServices', [])  
.controller('LogCtl', ['$scope', '$log', function($scope, $log) {   

      $scope.fnShowInfoMessage   = function(msg){   
       
          $log.info(msg);          
      };   
   
      $scope.fnShowWarningMessage = function(msg){  
        
          $log.warn(msg);          
      };    
  
      $scope.fnShowLogMessage = function(msg){
          
          $log.log(msg);          
      };  
    
      $scope.fnShowErrorMessage = function(msg){  
        
          $log.error(msg);          
      };  

  }]);


Refresh the web page and click the "Warning" button:

What are AngularJS Services and Dependency Injection   8


The Console reflects the warning message. Now do the same for the "Log" button:


What are AngularJS Services and Dependency Injection  9



And finally send an error message:

What are AngularJS Services and Dependency Injection    10



That's All!!! You have begun learning AngularJS Services and Dependency Injection in AngularJS , and using the $log service to send warnings, log, info and error messages to and from the app . In the next article we will continue to learn Step by Step about how to share data between different AngularJS Controllers by using Custom AngularJS $services
If you liked the CSS3 style, here you have the code to copy:

 div,input
{
padding:5px 5px 5px 25px;
margin:10px 15px 15px 25px;
font:900 12px Comic Sans MS;
opacity:0.9;
background:#fed;    
border:10px solid #ddd;    
border-radius: 10px;
box-shadow:10px 10px 2px #c0c0c0;
text-align:center;
}
input
{
padding:5px 5px 5px 25px;
margin:10px 15px 15px 25px;
font:900 12px Comic Sans MS;
opacity:0.9;
background:#FFF;    
border:10px solid #ddd;    
border-radius: 10px;
box-shadow:10px 10px 2px #c0c0c0;
text-align:center;
}
button 
{
padding:5px 5px 5px 5px;
margin:10px 15px 15px 15px;
width:220px;
text-align: center;
background:#ddd; 
font:900 14px Comic Sans MS;
opacity:0.9;
border:1px solid #c0c0c0;    
border-radius: 10px;
box-shadow:10px 10px 2px #c0c0c0;
}
ul
{
list-style:none;    
}

<<<<  PREVIOUS LESSON                               NEXT LESSON >>>>

Enjoy AngularJS.....

      by Carmel Schvartzman


כתב: כרמל שוורצמן