[英]Sharing data between angularjs services without a circular dependency error?
我正在嘗試構建一個角度應用程序,該應用程序將在不可靠的連接(即移動設備)下繼續運行。
到目前為止,我為每個模型都提供了服務(例如):
創建每個模型的新實例時,將獲得一個向導,直到我可以從服務器檢索到ID。
當我嘗試將它們連接到我的同步服務時,就會出現問題。 理想情況下,班級,學生和年級服務需要訪問同步服務,反之亦然,因此,可以將新對象傳遞給同步服務,然后在管理與服務器聯系以進行同步時,同步服務可以直接更新其服務中的模型。一個ID。 如果嘗試將服務相互注入,則會收到循環依賴項錯誤。
我該如何在這些服務之間共享數據? 我真的想嘗試避免重復代碼以跨每個單獨的服務同步模型(這也意味着更多的請求)?
編輯:
這是我想要實現的簡化示例:
angular.module('App')
.service('sync', function sync(students) {
var objectsToBeSynced = [];
function resync() {
// $http() to process and manage the pending objects
/**
* If request returns success, write into students.students[newIdFromServer] = students.students[oldId];
* then delete students.students[oldId];
*/
setTimeout(resync, 10000);
}
this.addToSync = function(object) {
objectsToBeSynced.push(object);
}
}
angular.module('App')
.service('students', function students(sync) {
var students = [];
this.students = students;
this.addStudent = function(student) {
sync.addToSync(student);
}
}
所有服務都取決於sync
服務。 因此,您只需要在其他服務中添加同步服務依賴項。
如果模型對象相同,則通過同步服務對模型所做的任何更改(例如替換ID)都將對其他三個服務可用。
您可以根據需要在服務上實現insert方法,以返回帶有更新對象的Promise。
更新:查看您的代碼,我仍然認為您不需要在sync
服務中添加對學生服務的引用,只要sync
服務所基於的對象與您的三個服務中的任何一個發送的對象相同即可。
所以
function resync() {
// $http() to process and manage the pending objects
/**
* If request returns success, and returns new id just update the existing object that is inside the objectsToBeSynced array, assuming you can correlate for which object you make request */
setTimeout(resync, 10000);
}
理想情況下,班級,學生和年級服務需要訪問同步服務,反之亦然,
我懷疑反之亦然。 類,學生和成績都應該能夠將數據傳遞到您sync
需要被同步到服務器服務。
聽起來有點像$http
,但是有一個隊列。 通常的Angular $http
不需要了解您的模型服務,它只接受數據並使用它。 您的sync
服務應該能夠執行相同的操作。
補充說明:我以前已經以類似的方式實現了一個過於復雜的隊列,但是后來我發現了HTTP攔截器 。 您可能想看看如何使用responseError
並在延遲或類似情況后自動重試任何請求。
通常$http
返回的$http
解決了這個問題,但是我假設您正在用一個新對象處理一個$http
,而不是多個$http
請求,每個對象一個嗎?
在那種情況下,我認為最好的解決方案是使用Angular事件。 對於每個newIdFromServer
,從sync
$emit
,並在每個需要newId
的對象中偵聽這些事件
.service('sync', function sync($rootScope) { // NOTE: inject $rootScope
var objectsToBeSynced = [];
function resync() {
// $http() to process and manage the pending objects
/* If request returns success, then for each new ID returned from
* server, do $rootScope.$emit('student.saveSucess', [oldId], [newIdFromServer]);
*/
setTimeout(resync, 10000);
}
this.addToSync = function(object) {
objectsToBeSynced.push(object);
}
})
.service('students', function students($rootScope, sync) { // NOTE: inject $rootScope
var students = [];
this.students = students;
this.addStudent = function(student) {
sync.addToSync(student);
}
$rootScope.$on('student.saveSucess', function(event, oldId, newIdFromServer) {
students.students[newIdFromServer] = students.students[oldId];
delete students.students[oldId];
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.