我在使用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服务,并且我正在引用更新的文档,因此觉得此更新的“问题/解决方案”很有必要。
有三种方法可以从$firebaseArray
对象中检索记录。
$getRecord(key)
$keyAt(recordOrIndex)
$indexFor(key)
我会更仔细地查看每个文档,但是根据您的描述,您可能想使用$keyAt
。但是请记住,这$firebaseArray
不是严格的数组,并且可用的方法提供了比“仅数组”中所提供的更多的选择/灵活性。
另外,如注释中所述,您希望在promise方法内部工作以为您处理数据绑定的三种方式。
var arrayRef = new Firebase(firebase_location).child(child_location);
var theList = $firebase(arrayRef).$asArray();
theList.$loaded(function (list) {
var x = list.$keyAt(list[target_position]);
//use other methods for the $firebaseArray object
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句