是的,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) { // 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。



