Angular Js Tutorial Part-7 - shiva tech

Latest

BANNER 728X90

Saturday 6 February 2016

Angular Js Tutorial Part-7

Hi Friend if you are fresher read my previous post of angular Js tutorial.

Today you will study about AngularJS services.

What is a ServiceServices are JavaScript functions and are responsible to do specific tasks only. AngularJS has about 30 built-in services. One of them is the $location, $http, $provide, $resource, $window, $parse service.

Different ways to create service in AngularJS: Factory

Factory is a simple function which allows you to add some logic before creating the object. It returns the created object.



<!DOCTYPE html>
<html>

<head>
    <title>Factory Demo</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">

    </script>
    <script>

        var app = angular.module('app', []);
        app.controller("MemberController", function($scope, myFactory)
        {
            $scope.FirstName = myFactory.FirstName;
            $scope.FullName = myFactory.FullName;
        });
        app.factory('myFactory', function()
        {
            varmyName = "Shiva";
            function getName()
            {
                return myName;
            }
            return
            {
                FullName: getName() + " " + "shukla",
                FirstName: getName()
            };
        });
    </script>
</head>
<body ng-app="app">
    <p>AngularJS Factory</p>


    <div ng-controller="MemberController">
        <p>
            FirstName: {{FirstName}}
        </p>
        <p>
            FullName: {{FullName}}
        </p>
    </div>
</body>


</html>  

Output


When to use: It is just a collection of functions like a class. Hence, it can be instantiated in different controllers when you are using it with constructor function.

Service: 

Service is a constructor function which creates the object using new keyword. You can add properties and functions to a service object by using this keyword. Unlike factory, it doesn’t return anything.



<!DOCTYPE html>
<html>

<head>
    <title>Service Demo</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">

    </script>
    <script>
        var app = angular.module('app', []);
        app.controller('MemberController', function ($scope, myService) {
            $scope.FirstName = myService.FirstName();
            $scope.FullName = myService.FullName;
        });
        app.service('myService', function () {
            varmyName = "Shiva";
            this.FirstName = function () {
                return myName;
            }
            this.FullName = myName + " " + "shukla"
        });
    </script>
</head>
<body ng-app="app">
    <p>AngularJS Service</p>
    <div ng-controller="MemberController">
        <p>
            FirstName: {{FirstName}}
        </p>
        <p>
            FullName: {{FullName}}
        </p>
    </div>
</body>


</html>
Output



When to use: It is a singleton object. Use it when you need to share a single object across the application.

Provider:
A provider is used to create a configurable service object. It returns value by using $get () function, $provide service has a number of methods for registering components with the $injector.



<!DOCTYPE html>
<html>

<head>
    <title>Provider Demo</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">

    </script>
    <script>

        var app = angular.module('app', []);
        app.config(["myProviderServiceProvider", function(myProviderService)
        {
            myProviderService.set("shiva", "shukla");
        }]);
        app.controller("MemberController", function($scope, myProviderService)
        {
            $scope.FirstName = myProviderService.FirstName();
            $scope.LastName = myProviderService.LastName();
            $scope.FullName = myProviderService.FullName;
        });
        app.provider('myProviderService', function()
        {
            var myFName = "Shiva";
            var myLName = "Shukla";
            return {
                set: function(fName, lName)
                {
                    myFName = fName;
                    myLName = lName;
                },
                $get: function()
                {
                    functiongetFName()
                    {
                        returnmyFName;
                    }
                    functiongetLName()
                    {
                        returnmyLName;
                    }
                    return
                    {
                        FullName: myFName + " " + myLName,
                        FirstName: getFName,
                        LastName: getLName
                    };
                }
            };
        });
    </script>
</head>
<body ng-app="app">
    <p>AngularJS Provider</p>


    <div ng-controller="MemberController">
        <p>
            FirstName: {{FirstName}} and LastName : {{LastName}}
        </p>
        <p>
            FullName: {{FullName}}
        </p>
    </div>

</body>


</html>
Output

When to use: 

When you need to provide module-wise configuration for your service object before making it available.

Value: You can also register a function as a value. Values are typically used as configuration which is injected into factories, services or controllers.




<!DOCTYPE html>
<html>

<head>
    <title>Value Demo</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">

    </script>
    <script>
        var app = angular.module('app', []);
        app.controller("MemberController", function ($scope, numberValue, stringValue, objectValue) {
            $scope.numberValue = numberValue;
            $scope.stringValue = stringValue;
            $scope.objectValue = objectValue;
        });
        app.value("numberValue", 1000);
        app.value("stringValue", "Hello Word");
        app.value("objectValue",
        {
            objVal1: true,
            objVal2: "My object Value"
        });
    </script>
</head>
<body ng-app="app">
    <p>AngularJS Value</p>

    <div ng-controller="MemberController">
        <p>
            number Value: {{numberValue}}
            <br /> string Value: {{stringValue}}
            <br /> object Value : {{objectValue.objVal1}} and {{objectValue.objVal2}}
        </p>
    </div>
</body>


</html>  

Output:

Constant:It is like a value. Register a constant service, such as a string, a number, an array, an object or a function, with the $injector. Unlike value it can be injected into a module configuration function and it cannot be overridden by an Angular decorator.



<!DOCTYPE html>
<html>

<head>
    <title>Constant Demo</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">

    </script>
    <script>
        var app = angular.module('app', []);
        app.controller('MemberController', function ($scope, myConfig) {
            $scope.myConfig = myConfig;
        });
        app.constant('myConfig',
        {
            flag: true,
            settings: "default"
        });
    </script>
</head>
<body ng-app="app">
    <p>AngularJS Constant</p>
    <div ng-controller="MemberController">
        <p>
            flag: {{myConfig.flag}}
            <br /> settings: {{myConfig.settings}}
        </p>
    </div>

</body>


</html>  

Output:



Decorator: A decorator can modify or encapsulate other providers. There is one exception and that a constant cannot be decorated.

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

app.value('movieTitle', 'Airlift');

app.config(function($provide)
{
    $provide.decorator('movieTitle', function($delegate)
    {
        return $delegate + ' – The rising';
    });
});

app.controller('MyController', function(movieTitle)
{
    expect(movieTitle).toEqual('Airlift – the rising');


});  

Summary: 
  • All the providers are instantiated only once. That means that they are all singletons.
  • All the providers except constant can be decorated.
  • A constant is a value that can be injected everywhere. The value of a constant can never be changed.
  • A value is just a simple injectable value.
  • A service is an injectable constructor.
  • A factory is an injectable function.
  • A decorator can modify or encapsulate other providers except a constant.
  • A provider is a configurable factory.

No comments: