AngularJS > Components

Dependency Injection in AngularJS

What Dependency Injection in AngularJS?


Dependency injection is a software design pattern that states that instead of creating an instance of a dependent service or object when we need, the class or function should ask for it.

The Angular injector system is responsible to create the component, services, and resolve dependencies of those services or objects and provide to the calling class or functions.

        // No dependency injection
        function GetData() {
            var $http = new HttpService();
            return $http.get("/Article/getData");
        }

        // Dependency injection
        function GetData($http) {
            return $http.get("/Article/getData");
        }

  • In the first function, a new instance of $http is created every time the GetData() function is called.

    The disadvantage of this approach is following

    • It creates a new instance of of the HttpService in this function, any change to this object need change in each implementation wherever this object is instantiated.
    • The same instance of HttpService() can't be used in more than one function.

  • In the second function, $http service instance is passed to the function itself.

    The benefit of this approach is following

    • Change to the $http declaration at once place, brings change to all dependent function that uses this

AngularJS guarantees only one instance of the dependent object and all other dependent function gets the same instance of the object. This is done using Singleton design pattern and the same instance remains available in the entire scope of the application (in the whole web page). It means that two or more controllers or services or function asking for this $http service gets the same instance of the object.

 Views: 11064 | Post Order: 14




Write for us






Hosting Recommendations