【问题标题】:return $add ref of Firebase item AngularFire返回 Firebase 项目 AngularFire 的 $add ref
【发布时间】:2014-02-02 16:54:04
【问题描述】:

假设我有一个项目集合:

var itemsRef = new Firebase("https://example.firebaseio.com/items");  
$scope.items = $firebase(itemsRef);

我们$add一个项目:

$scope.items.$add($scope.item);

我了解 ref 在进入 Firebase 集合之前会在客户端生成。

添加项目后如何获得该 ref? 例如 -Jx8363hdu12

AngularFire 0.6.0

【问题讨论】:

    标签: javascript angularjs firebase angularfire


    【解决方案1】:

    截至 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());
    });
    

    【讨论】:

      【解决方案2】:

      如果您有以前使用过的代码,其他人会来到这里

       var bleh = $scope.items.$add($scope.item);
      

      以前 $add 会返回实际值,但正如 Dan 上面提到的,它被更改为返回一个 Promise。

      你有两个选择(越晚越好)。

      1. 回到旧版本的 angularfire。
      2. 您必须使用 .then 操作。

      我遇到过几次这个问题,并且一直遇到这个问题(我希望可以找到更多的术语变化,如果它再次发生在我或其他人身上,它会更容易找到)。

      在我的脑海中,一个承诺意味着你仍然可以使用该变量,并且在将来的某个时候它会填充它(所以我一直认为它最终会填充它并且对它感到恼火似乎从来没有)。

      从这里: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 在保存数据时出错(添加/删除/等),你至少应该有错误功能,这样你就可以捕捉到发生了错误。

      以丹为例:

      $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);
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-12-24
        • 1970-01-01
        • 2020-05-16
        • 1970-01-01
        • 1970-01-01
        • 2015-11-15
        • 1970-01-01
        相关资源
        最近更新 更多