如何将异步函数结果返回并保存到AngularFire中的firebase

时间:2016-04-29 11:49:05

标签: angularjs firebase angularfire

我在下面创建了这项服务。

app.factory('userProfileFactory', ['FBDB', 'searchParam', function(FBDB, searchParam) {
        var personalKey;
    return {

        userProfile: function(searchEmail) {
          var deferred = $q.defer();
          var FBref = new Firebase(FBDB).child('items');
          var promise = FBref.orderByChild('email')
                .startAt(searchEmail)
                .endAt(searchEmail)
                .on('value', function(snapshot) {
                  var data = snapshot.val();
                  personalKey = Object.keys(data)[0];
                  deferred.resolve(personalKey);
                });
          return deferred.promise;
        }
    };
}]);

我的控制器如下。问题是返回结果需要一些时间。因此,当$ save函数在工厂函数外部调用时,它会报告一个“未定义的变量”。当$ save在外面时,我怎样才能使它工作?

app.controller('profileCtrl', ['userProfileFactory', 'FBDB', '$firebaseArray', function(userProfileFactory, FBDB, $firebaseArray) {

var FBref = new Firebase(FBDB).child('items');

     userProfileFactory.userProfile().then(function(res){
         var personalKey = res;

        item.personalKey = res;

        //$firebaseArray(FBref)$save(item);  It works here. But moved this from here... 
    })

     $firebaseArray(FBref)$save(item); //...to here. It does not work.

}]);

1 个答案:

答案 0 :(得分:0)

在您的代码中,行:

$firebaseArray(FBref)$save(item);

将在resolve函数之前执行:

function(res){
     var personalKey = res;

    item.personalKey = res;
}

resolve function等待userProfileFactory.userProfile()promise在执行之前解析(要返回的数据),而firebase.save行则不会。你需要把它放回then(解决)函数。