Wednesday, December 24, 2014

Inject one service into another service in AngularJS

The philosophy behind implementation of service is to use same functionality in more than one place. In angular service are singleton component across application.

As it is singleton, we need not to create particular object to call/consume service. In Angular, we can inject any service to any other component (read controller) and consume the service within this component.

There might be some scenario, where we might create one base service and want to consume the base service from any other services.

In this example, we will learn to inject one service to another service using DI pattern of Angular and we will consume the base service within it.


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

        app.service('messageService', function () {
            var success = function () {
                return "success";
            };

            return {
                success: success
            };
        });

The ‘messageService’ is the base service, which is, attach with app module.  We have implemented success function which will return “success” string as ,message once it get call.

Fine, now we will implement another service and will inject messageService into it. Here is code implementation.

        app.service('messageConsumer', function (messageService) {

            var successProxy = function () {
                var data = messageService.success();
                if (data == 'success') {
                    return "executed successfully"
                }
            }

            return {
                success: successProxy
            }
        });


The implementation is pretty simple, just we are injecting service name into it. Now , successProxy function will internally call message to get data from base service.

Here, is one sample controller which again consuming “messageConsumer” service into it.

        app.controller('myController', function (messageConsumer) {

            alert(messageConsumer.success());

        });

And we will get below output once we call “myController” from application.


No comments:

Post a Comment