假设我有一系列项目:
var itemsRef = new Firebase("https://example.firebaseio.com/items");
$scope.items = $firebase(itemsRef);
我们$add
项目:
$scope.items.$add($scope.item);
我知道在进入Firebase集合之前,ref会在客户端生成。
如何在添加商品后获得该参考? 例如 -Jx8363hdu12
AngularFire 0.6.0
答案 0 :(得分:6)
从 AngularFire 0.6.0 $add
开始,$save
,$set
和$remove
使用承诺:
https://github.com/firebase/angularFire/issues/183
$scope.items.$add($scope.item).then(function(p){
console.log(p.name());
});
答案 1 :(得分:1)
对于其他来到这里的人,如果您有以前使用
工作的代码 var bleh = $scope.items.$add($scope.item);
以前$ add会返回实际值,但正如上面提到的那样,它被更改为返回一个承诺。
你有两个选择(后者更好)。
我已经遇到过这个问题并继续遇到它(我希望可以找到更多的术语变化,如果它再次发生在我或其他人身上会更容易找到)。
我脑子里有一个承诺意味着你仍然可以使用这个变量,并且在未来的某个时候它会填补它(所以我一直认为它会最终填补它并且让它变得烦恼它似乎从来没有。
从这里开始:http://www.html5rocks.com/en/tutorials/es6/promises/
Here's how you use that promise:
promise.then(function(result) {
console.log(result); // "Stuff worked!"
}, function(err) {
console.log(err); // Error: "It broke"
});
"then" takes two arguments, a callback for a success case, and another for the failure case. Both are optional, so you can add a callback for the success or failure case only.
所以理论上如果firebase错误输出保存数据(添加/删除/等),你至少应该有错误功能,这样你就可以发现错误发生了。
对于Dan的例子:
$scope.items.$add($scope.item).then(
function(p){
console.log(p.name());
},
function(err){
console.log("The expected Firebase action failed to occur this was your error: " + err);
});