2015-06-19 25 views
1

我覺得我必須錯過一些非常基本的東西。以下是我服務的一部分:

angular.module('fire') 
    .constant('FIREBASE_URI', 'https://___.firebaseio.com/') 

    .factory('syncArraySvc', function(FIREBASE_URI, $firebaseArray) { 

    var buildingsUri = FIREBASE_URI + "buildings"; 
    var buildings = $firebaseArray(new Firebase(buildingsUri)); 
    console.log(buildings); 

    var getBuildings = function() { 
     return buildings; 
    }; 
    var addBuilding = function(item) { 
     buildings.$add(item); 
    }; 
    return { 
     getBuildings: getBuildings, 
     addBuilding: addBuilding 
    }; 
    }); 

中間的console.log只是返回一個空數組。如果我嘗試從另一個控制器調用syncArraySvc.getBuildings()函數,我也會得到一個空數組。不知何故,$add(item)的作品,如syncArraySvc.addBuilding(item)。我錯過了什麼?

回答

1

其他答案幫助我指出了正確的方向。

API documentation有一個代碼示例,似乎並不需要的數據被包裹在一個承諾:

var list = $firebaseArray(new Firebase(URL)); 
$scope.list = list; 

但是,它並指出,你可以使用$loaded承諾要通知時數據被加載。這是我得到了它在我的項目工作:

syncArraySvc.getBuildings().$loaded(function(data) { 
    $scope.buildings = data; 
}); 

我想在一個新的項目複製此,它一貫致力於無$loaded包裝,就像他們在第一個例子顯示。我認爲$loaded包裝將是必需的。我不明白如果沒有它,它會如何在第一個例子中工作。

+1

'$ loaded'承諾在加載* initial *數據時解析。當附加項目添加到數組時,它不*解析*。所有你需要做的是'$ scope.buildings = $ firebaseArray(new Firebase(buildingsUri))'。請不要使用'console.log'來調試AngularFire數據,這很容易導致誤解。相反,只是把這個地方放在你的視圖中:'

buildings | json
' –

+0

@FrankvanPuffelen我的上面的答案會確保數據已被添加或沒有..我相信它肯定會工作並顯示更新的數據 –

+0

要正確地擴展'$ firebaseArray' ,閱讀:https://www.firebase.com/docs/web/libraries/angular/guide/extending-services.html#section-firebasearray –

0

嘗試在getBuildings函數中使用$timeout服務,或者更確切地說,當您調用它時。數據返回之前可能需要一些時間。

2

如果您看$ add $firebaseArray,它確實會創建新項目&將其添加到$firebaseArray中,就像我們有buildings一樣。但只要將項目添加到``firebaseArray`中,它就不會立即添加。當$ add promise得到解決時它會被添加。

我想你是在做正確的事情,只有你需要撥打syncArraySvc.addBuilding(item)方法才能成功$add的承諾。

爲了使這個方法,你需要從服務方法返回一個承諾像

var addBuilding = function(item) { 
    return buildings.$add(item); 
}; 

然後是調用函數將採取這一承諾,並在它的決心,他會叫syncArraySvc.addBuilding(item)方法有assurity那物品已添加到buildings陣列中。

syncArraySvc.addBuilding({foo: "bar"}).then(function(addedItem){ 
    console.log(addedItem); 
    console.log(syncArraySvc.addBuilding(item)); //this will show you updated list 
}) 
相關問題