0

What is the magic behind auto resolving dependencies in AngularJS?

angular
    .module('app', [])
    .service('appService', 
        function appService (firstService, secondService, thirdService) { }

How are firstService, secondService, thirdService automatically injected?

1

1 Answer 1

1

JavaScript Automatic Dependency Injection is based on Function.prototype.toString() method that returns a string representation of the object in the form of a function declaration.

The returned string is parsed with regular expression to find function arguments and return its names that will be used to find, instantiate and inject real services.

(function appService (firstService,secondService,thirdService) {})
    .toString()
    .match(/^function\s*[^\(]*\(\s*([^\)]*)\)/m)[1]
    .split(',')

// => ["firstService", "secondService", "thirdService"]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.