【发布时间】:2015-05-13 20:55:46
【问题描述】:
我在使用 AngularFire / Firebase 从集合中获取单个记录时遇到了一些麻烦(然后,在我拥有它之后,将它从集合中删除)。我相信我正在关注位于此处的正确文档:https://www.firebase.com/docs/web/libraries/angular/api.html#angularfire-firebasearray
注意:我发现的许多文档/博客/答案似乎都在使用已弃用的 $firebase 服务(使用 $asArray 方法) - 但是,最近的文档确定 $firebaseArray 是正确使用的服务,仅供参考。
出于某种原因,即使我可以准确地提取民意调查集合,我也无法提取单个元素(尽管官方文档似乎与我使用的语法相同)。
$remove (https://www.firebase.com/docs/web/libraries/angular/api.html#angularfire-firebasearray-removerecordorindex) 的文档:
## official docs ##
$remove(recordOrIndex)
Remove a record from Firebase and from the local data. This method returns
a promise that resolves after the record is deleted at the server. It will
contain a Firebase reference to the deleted record. It accepts either an
array index or a reference to an item that exists in the array.
var list = $firebaseArray(ref);
var item = list[2];
list.$remove(item).then(function(ref) {
ref.key() === item.$id; // true
});
我的代码(见下面的 console.log):
.service('pollsData', function($firebaseArray){
var fireRef = new Firebase('<-my-firebase-ref-url>');
var polls = $firebaseArray(fireRef.child('polls'));
var service = this;
this.clearPolls = clearPolls;
this.setInitialPolls = setInitialPolls;
this.getPolls = getPolls;
function clearPolls() {
console.log("length: ", polls.length); <--- I get a length of 0
console.log(polls); <-- I get a $firebaseArray object including the methods in the API docs
console.log(polls[0], polls[1], polls[2]); <--- all 3 are undefined even though I can see several in the firebase data dashboard
var poll = polls[1];
console.log("poll?: ", poll);
polls.$remove(poll);
}
function getPolls() {
polls = polls || $firebaseArray(fireRef.child('polls'));
return polls; <-- I can successfully ng-repeat over this returned selection in the template
}
function setInitialPolls() {
service.clearPolls();
polls.$add({
one: {
name: "fantastic pollllllls",
selection_one: {
name: "pizza",
count: 0
},
selection_two: {
name: "fries",
count: 0
}
},
two: {
name: "mediocre poll",
selection_one: {
name: "blue",
count: 0
},
selection_two: {
name: "green",
count: 0
}
}
});
}
setInitialPolls();
});
关于为什么从 $firebaseArray 中提取记录的方括号 [] 符号不能按 AngularFire 文档的预期工作的任何见解?
更新:提供的回复仍然很有帮助,因为这似乎与我对 $firebaseArray 的较新文档以及 API 文档中 $remove 部分给出的示例的理解相冲突。了解这从根本上仍然是一个异步问题,但是由于 $firebase 服务已被弃用并且我正在参考更新的文档,因此觉得这个更新的问题/解决方案是必要的。
【问题讨论】:
-
在修改了一些之后,它似乎确实是一个异步问题。也就是说,我不完全确定 何时/何地 在 firebase 返回后我能够解决,特别是因为(根据我上面粘贴的文档)文档没有在这里指出异步性质。
-
@SinanBolel 在这里是正确的,但原因可能不是很明显。有关详细信息,请参阅重复链接。本质上,您已经向服务器发出了异步数据请求,但随后立即尝试利用所述数据而不等待其加载。
-
感谢@Kato 的扩展回答
标签: angularjs firebase angularfire