Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.
This repository was archived by the owner on Apr 12, 2024. It is now read-only.

Dependency injection of custom service into another custom service #590

Closed
@lukaszdechovan

Description

@lukaszdechovan

I want to use dependency injection in my custom angular services.
I have one simple service A and another simple service B. When I inject these two to a controller, everything works as expected. However, when I try to use service A in service B and I want to inject A to the B service, nothing is injected (parameter where should be instance of Service B is undefined).

Is this a bug, angular doesn't support injection of custom service into another custom service by design, or I just made some mistake?

Here are the code snippets of my app:

File ServiceA.js

var ServiceA = function ($log) { // angular service $log is successfuly injected
    alert("Service initialized"); 
    
    this.showMessage = function(message) {
         alert(message);
    };   
};
ServiceA.$inject = ["$log"];

File SerivceB.js

var ServiceB = function (serviceA) { // serviceA is undefined
    alert("Service initialized");
 
    serviceA.showMessage("method of serviceA called from serviceB"); // this row throws an error of course
};
ServiceB.$inject = ["ServiceA"];

File index.html

.... jQuery, angular.js, etc...

<script type="text/javascript" src="ServiceA.js"></script>
<script type="text/javascript" src="ServiceB.js"></script>

<script type="text/javascript">
    angular.service('ServiceA', function () {
        return new ServiceA();
    });    

    angular.service('ServiceB', function () {
        return new ServiceB();
    });    

    function FormController(serviceA, serviceB) {
        this.user = {
            name: 'John Smith',            
        };        
    }
    FormController.$inject = ['ServiceA', 'ServiceB'];
  </script>

  <div ng:controller="FormController" class="example">    
      .... some HTML Markup ....
  </div>
   .... end of the page...

Thanks for your answers and advices.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions