小编典典

隐式/内联/ $ inject依赖注入在AngularJS中如何工作?

angularjs

我是AngularJS的新手,我想了解更多有关默认注入的依赖项的信息。在阅读代码时,我注意到有时依赖项是事先明确声明的,有时则不是。例如:

someModule.controller('MyController', ['$scope', 'someService', function($scope, someService) {
  // ...
}]);

给出与以下结果相同的结果:

someModule.controller('MyController', function($scope, someService) {
  // ...
});

这是如何运作的?Angular是否假设要注入的模块的名称与参数中的变量相同?

同样,奇怪的是,如果您确实指定将要注入的依赖项,则必须以 正确的顺序 指定 所有 依赖项,否则将无法正常工作。例如,这是损坏的代码:


someModule.controller('MyController', ['someService', '$scope', function($scope, someService) {
  // Won't give us any errors, but also won't load the dependencies properly
}]);

有人可以向我说明整个过程如何运作吗?非常感谢你!!


阅读 344

收藏
2020-07-04

共1个答案

小编典典

是的,Angular中的依赖项注入通过您注册的组件(和Angular-内部组件)的名称起作用。

下面的示例显示了如何使用几种不同的注释将服务注册并注入到控制器中。请注意,依赖注入在Angular中始终相同,即,是否向控制器,指令或服务中注入某些东西都没有关系。

app.service('myService', function () {
    // registering a component - in this case a service
    // the name is 'myService' and is used to inject this
    // service into other components
});

在其他组件中有两个使用(注入)此组件的方法,我知道三个不同的注释:

1.隐式注释

您可以指定一个构造函数,该函数将所有依赖项作为参数。是的,名称必须与注册这些组件时的名称相同:

app.controller('MyController', function ($http, myService) {
    // ..
});

2.内联数组注释

或者,您可以使用数组表示法,其中最后一个参数是具有所有可注入对象的构造函数(在这种情况下,变量名称无关紧要)。数组中的其他值必须是与可注射物名称匹配的字符串。Angular可以通过这种方式检测注射剂的顺序并适当地进行检测。

app.controller('MyController', ['$http', 'myService', function ($h, m) {
    /* Now here you can use all properties of $http by name of $h & myService by m */
    // Example
    $h.x="Putting some value"; // $h will be $http for angular app
}]);

3. $ inject属性注释

第三种选择是$inject在构造函数上指定-property:

function MyController($http, myService) {
    // ..
}
MyController.$inject = ['$http', 'myService'];
app.controller('MyController', MyController);

至少据我所知,最后两个选项可用的原因是由于在缩小JavaScript文件时发生的问题导致了参数名被重命名。然后,Angular无法检测到要注入的东西。在后两种情况下,将可注射物定义为细线,在细化过程中不会触碰。

我建议使用版本2或3,因为版本1不适用于缩小/混淆。我认为版本3是最明确的。

您可以在Internet上找到一些更详细的信息,例如Angular Developer
Guide

2020-07-04