Angular框架里两个模块的互相依赖

  • 2020 年 2 月 15 日
  • 笔记

如果把思路放宽一点,把狭义的死锁场景中对资源的并发请求,拓宽到编程中的依赖管理,那么我们可以构造一个循环依赖的场景,即模块A和模块B互相依赖。 可以很容易地用一个不到20行的Angular应用来模拟循环依赖的场景。

<html ng-app="test">  <head>      <title>Angular Circular Dependency Example</title>  </head>  <body ng-controller="testController">      Test  </body>  <script type="text/javascript">      var module = angular.module('test', []);        module.service('service1', function(service2) {});      module.service('service2', function(service1) {});        module.controller('testController', function(service1) {});  </script>  </html>

执行这个Angular应用,遇到Angular框架报的错误信息:

VM17 angular.js:14802 Error: [injector:cdep]Circulardependencyfound:service1<−service2<−service1http://errors.angularjs.org/1.6.9/injector:cdep] Circular dependency found: service1 <- service2 <- service1 http://errors.angularjs.org/1.6.9/injector:cdep]Circulardependencyfound:service1<−service2<−service1http://errors.angularjs.org/1.6.9/injector/cdep?p0=service1%20%3C-%20service2%20%3C-%20service1

at VM17 angular.js:116 at getService (VM17 angular.js:5041) at injectionArgs (VM17 angular.js:5074) at Object.instantiate (VM17 angular.js:5120) at Object. (VM17 angular.js:4955) at Object.invoke (VM17 angular.js:5108) at Object.enforcedReturnValue [as $get] (VM17 angular.js:4939) at Object.invoke (VM17 angular.js:5108) at VM17 angular.js:4893 at getService (VM17 angular.js:5049) 按照在代码中的出现顺序,首先执行service1的注入。既然是第一次注入,因此代码第5039行cache里肯定不存在service1对应的实例,所以进入5045行的else分支,调用factory方法进行service1的实例化。

因为service1依赖于service2,所以service1实例化的时候触发了service2的实例化:

而service2又依赖于service1,此时Angular在cache里检测到service1还处于正在实例化的阶段,为了避免这种循环依赖,Angular框架直接报exception.