2014-10-30 39 views
0

我有以下服務:如何AngularJS:連接兩種服務相互

DataService的(應該從apiService獲取數據,然後排序/組/過濾數據)。 apiService(應該從服務器獲取數據。而且,當更新的數據進入(websockets)時,數據應該被推送到dataService)。

現在,看起來,兩個服務不能互相連接。 我的dataService如何獲取更新?我下面的想法,但林不知道,如果這是最好的做法:

  • DataService的調用apiService.init()
  • 在apiService.init():從API/Server和安全它VAR獲取數據數據
  • dataService然後通過$ watch從apiService.data獲取數據,因此每次數據更新時都會通知dataService。

您怎麼看?有沒有更好的方法來做到這一點?非常感謝你!

編輯:

這不會工作:

var apiService = angular.module('apiService', []); 

apiService.service('apiService', ['$http', 'dataService', function($http, dataService) { 
    return { 
     foo: "foo" 
    }; 
}]); 


var dataService = angular.module('dataService', []); 

dataService.service('dataService', ['$http', 'apiService', function($http, apiService) { 
    return { 
     foo: "foo" 
    }; 
}]); 

編輯2:

會告訴我在Firebug:

錯誤:[$注射器:CDEP] http://errors.angularjs.org/1.2.26/ $ injector/cdep [...]

+2

似乎罰款...什麼是錯的/有什麼問題嗎? – tymeJV 2014-10-30 14:45:46

+0

如果有更好的方法來做到這一點,甚至更好,如果有一種好方法可以使兩個服務能夠相互通信。 – Tream 2014-10-30 14:53:39

+0

您的2個服務與eachother進行通信.. – tymeJV 2014-10-30 14:55:12

回答

1

由於它們之間的循環依賴性,您的服務無法工作。

你提出的解決方案應該可以正常工作,但可以通過承諾進一步改善,如下面的僞代碼:

var apiService = angular.module('apiService', []); 
 

 
// Note that 'apiService' no longer has 'dataService' as a dependency 
 
apiService.factory('apiService', ['$http', 
 
    function($http) { 
 
    return { 
 
     get: function() { 
 
     // Return $http promise 
 
     return $http.get(...); 
 
     } 
 
    }; 
 
    } 
 
]); 
 

 

 
var dataService = angular.module('dataService', []); 
 

 
// Now, only 'dataService' depends on 'apiService' 
 
dataService.factory('dataService', ['$http', 'apiService', 
 
    function($http, apiService) { 
 
    return { 
 
     // This can further return a promise like below 
 
     get: function() { 
 
     return apiService.get() 
 
      // Execute 'then' once the promise returned by the apiService.get() is resolved (i.e. date received) 
 
      .then(function(response) { 
 
      console.log(response); 
 
      }) 
 
     } 
 
    }; 
 
    } 
 
]);