Angularjs - how to correct inject service from ano

2019-04-21 13:33发布

问题:

I didn't understand how work modular depending.

I have 3 modules, they are dependent on each other, as shown in the picture.

"App" module includes "module1" and "module2". "module2" includes "core" module. There are source on plunker.

angular.module("core", []).factory("HelloWorld", function() {
  return function () {
    alert('Hello World!')
  }
});

angular.module("module1", []).controller("main", function(HelloWorld){
  HelloWorld();
});

angular.module("module2", ["core"]);

angular.module("app", ["module1", "module2"]);

If I inject service from module core to module "module1" it is work fine. But "core" module not depend in module "module1". Why it happening?

回答1:

Since your App module depends on Core module (indirectly through Module 2), the services in Core module are available anywhere inside your App module (including Module 1).

This is because Angular will first load all modules and then start instantiating their components and resolving injected dependencies.

Yet, if you indeed need Core services in Module 1, you should make it dependent on the Core module as well. That way your application won't break if Module 2 is modified at a later time (or removed altogether) and your Module 1 will be more self-contained and reusable (e.g. you could use it with a different application that does not depend on the Core module).

In general, you should not rely on "indirect" dependencies. Each module should explicitly declare its dependencies.
Angular is smart enough to only load a module if it is not already loaded, so there is no overhead.

Quoting from the Developer Guide's section on modules:

Modules can list other modules as their dependencies. Depending on a module implies that required module needs to be loaded before the requiring module is loaded. In other words the configuration blocks of the required modules execute before the configuration blocks of the requiring module. The same is true for the run blocks. Each module can only be loaded once, even if multiple other modules require it.

(emphasis mine)