Need to understand Dependency Injection in Angular.js

后端 未结 2 657
伪装坚强ぢ
伪装坚强ぢ 2021-01-03 13:04

I am a newbie in Angular.js and came across a topic called \"Dependency Injection\". I am totally confused after reading the article.

As per the doc

相关标签:
2条回答
  • 2021-01-03 13:49

    Dependency injection allows you to do several things, first it allows for you to specify only what you need in your controller, factory, service, etc.

    You have a lot of pre-baked options but injection also allows you to incorporate 3rd party Angular modules into your project.

    For example, let's say you want to use animations and routing, but you want to use ui-router instead of ngRoute than you would inject them into your app instantiation.

    var myApp = angular.module('myApp', ['ui.router', 'ngAnimate']);
    

    Now let's say you have your first controller setup.

    But let's say you have a service that you want to use in that controller that handles all of your ajax calls using promises.

    First the service would be setup with injecting $http to make the server request and $q for the promises.

    // It is important to note that not all modules have a scope, 
    // so injecting scope into this service would cause a fatal error, 
    // it is important to become familiar with what baked in modules allow for 
    // injections.
    myApp.service('myAjax', function ($http, $q) {
        return {
            getUsers: function () {
                var q = $q.defer();
                $http.get('my/url/path').success(function (results) {
                    // We got a successful response so pass on the results
                    q.resolve(results);
                }).error(function (errorResults) {
                    // Something went wrong, let's pass that along
                    q.reject(errorResults);
                });
                return q.promise;
            }
        }    
    });
    

    Now that we have the service setup, we would inject that into our controller so we can easily use it to get the users or do anything else we declared in there:

    // Note that I am demonstrating a different injection approach, this is actually the recommended approach
    myApp.controller('myController', ['$scope', 'myAjax', function ($scope, myAjax) {
        // call our service
        myAjax.getUsers().then(
            function (results) {
                // Here we are using our controller $scope injection to 
                // bind to the html
                $scope.users = results;
            },
            function (error) {},
        )
    }]);
    

    Edit

    $inject is part of $injector which you can find more information here.

    $injector gets instances of everything that has been injected and $inject just allows you to setup the injection parameters. $injector runs behind the scenes.

    Here is a snippet from the angular source on github - Line 1238

    angular.module('ngAppStrictDemo', [])
    // BadController will fail to instantiate, due to relying on automatic function annotation,
    // rather than an explicit annotation
        .controller('BadController', function($scope) {
            $scope.a = 1;
            $scope.b = 2;
        })
        // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,
        // due to using explicit annotations using the array style and $inject property, respectively.
        .controller('GoodController1', ['$scope', function($scope) {
            $scope.a = 1;
            $scope.b = 2;
        }])
        .controller('GoodController2', GoodController2);
    function GoodController2($scope) {
        $scope.name = "World";
    }
    GoodController2.$inject = ['$scope'];
    
    0 讨论(0)
  • 2021-01-03 13:57

    I want to share of what I thought was a really great example of DI. I'm taking this example from the Angular.js documentation.

    angular.module('xmpl.service', [])
    
      .value('greeter', {
        salutation: 'Hello',
        localize: function(localization) {
          this.salutation = localization.salutation;
        },
        greet: function(name) {
          return this.salutation + ' ' + name + '!';
        }
      })
    
      .value('user', {
        load: function(name) {
          this.name = name;
        }
      });
    
    angular.module('xmpl.directive', []);
    
    angular.module('xmpl.filter', []);
    
    angular.module('xmpl', ['xmpl.service', 'xmpl.directive', 'xmpl.filter'])
    
      .run(function(greeter, user) {
        // This is effectively part of the main method initialization code
        greeter.localize({
          salutation: 'Bonjour'
        });
        user.load('World');
      })
    
      .controller('XmplController', function($scope, greeter, user){
        $scope.greeting = greeter.greet(user.name);
      });
    

    This code defines a separate module for directive, filter and service. As written in the documentation:

    Run blocks are the closest thing in Angular to the main method.

    So, the xmpl module has 3 dependencies which are injected using DI.

    0 讨论(0)
提交回复
热议问题