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.