我試圖從Firebase數據庫中檢索數據,並從Firebase存儲中檢索相應的圖片。問題是,我的觀點不想用數據更新自己。更新後的範圍變量未顯示在視圖中。承諾無效
如果我試圖簡單地從我的數據庫中獲取數據,它可以很好地工作。一旦我添加獲取圖片的功能(需要稍微長一些),它看起來像我的視圖只是立即查看範圍變量,並不等待$ scope.friendsinfo更新。我認爲我在承諾中做錯了什麼,應該使用$ q,但我不知道具體如何。誰能告訴我什麼是最好的方式去做這件事?非常感謝!
var friendsRef = firebase.database().ref('friendships/' + firebase.auth().currentUser.uid);
$scope.friends = $firebaseArray(friendsRef);
$scope.friendsinfo = [];
$scope.$watch('friends', function() {
var newfriends = $scope.friends;
var newfriendsinfo = [];
for(var i = 0; i < newfriends.length; i++){
var ref = firebase.database().ref('users/' + newfriends[i].$id);
var profilePicRef = firebase.storage().ref("profilepictures/" + newfriends[i].$id + "/profilepicture");
var picPromise = fetchPicture(profilePicRef);
var newfriendid = newfriends[i].$id;
var newfriendagreed = newfriends[i].agreed;
picPromise.then(function(data){
ref.once('value', function(snapshot){
newfriendsinfo.push({
id: newfriendid,
name: snapshot.val().name,
email: snapshot.val().email,
agreed: newfriendagreed,
profilepicture: data //This is the functionality that causes my view to not display the updated $scope.friendsinfo because it takes too long.
});
});
});
}
$scope.friendsinfo = newfriendsinfo;
alert($scope.friendsinfo.length);
}, true);
function fetchPicture(ref){
return ref.getDownloadURL().then(function(url) {
return url;
}).catch(function(error) {
alert("error");
});
}