我在下面创建了这项服务。
app.factory('userProfileFactory', ['FBDB', 'searchParam', function(FBDB, searchParam) {
var personalKey;
return {
userProfile: function() {
var FBref = new Firebase(FBDB).child('items');
FBref.orderByChild('first')
.startAt(searchParam)
.endAt(searchParam)
.once('value', function (snapshot) {
var data = snapshot.val();
personalKey = Object.keys(data)[0];
return(personalKey);
});
return(personalKey);
}
};
}]);
但是,当我尝试在下面的控制器中获取personalKey的值的结果时,我得到" undefined":
app.controller('profileCtrl', ['userProfileFactory', function(userProfileFactory) {
console.log(userProfileFactory.userProfile())
}]);
请建议:)
答案 0 :(得分:3)
是的,您可以通过$q
userProfile: function() {
var deferred = $q.defer();
var FBref = new Firebase(FBDB).child('items');
var promise = FBref.orderByChild('first')
.startAt(searchParam)
.endAt(searchParam)
.on('value', function(snapshot) {
var data = snapshot.val();
personalKey = Object.keys(data)[0];
deferred.resolve(personalKey);
});
return deferred.promise
}
然后控制器将使用.then
函数调用工厂函数来链接承诺。
app.controller('profileCtrl', ['userProfileFactory', function(userProfileFactory) {
userProfileFactory.userProfile().then(function(res){
console.log(res);
})
}]);