AngularJs返回异步工厂?
我读了很多关于这个问题的答案,但我就是不明白。承诺到哪里去了?我通过对云数据库的异步调用创建了一个简单的工厂:AngularJs返回异步工厂?,angularjs,firebase,asynchronous,angular-promise,Angularjs,Firebase,Asynchronous,Angular Promise,我读了很多关于这个问题的答案,但我就是不明白。承诺到哪里去了?我通过对云数据库的异步调用创建了一个简单的工厂: app.factory('asyncFactory', function() { let toController = function() { firebase.database().ref('en').once('value') // get the array from the cloud database .then(function(snapshot)
app.factory('asyncFactory', function() {
let toController = function() {
firebase.database().ref('en').once('value') // get the array from the cloud database
.then(function(snapshot) { // take a snapshot
console.log(snapshot.val()); // read the values from the snapshot
return snapshot.val(); // this returns later
});
return 47 // this returns immeadiately
};
return {
toController: toController // why is this necessary?
}
});
我从控制器中调用它:
$scope.words = asyncFactory.toController();
console.log($scope.words);
以下是回应:
如您所见,47
立即返回控制器。如果我注释掉return 47
,则工厂返回undefined
。稍后会记录异步数据,但不会返回控制器。我每天都用承诺,但我不知道承诺会去哪里
第二个问题:我是否需要行到控制器:到控制器
?我能把它处理掉吗
谢谢 好的控制者正在为自己吃掉承诺。(无论何时调用.then(),都表示您在等待承诺), 试试这个
app.factory('asyncFactory', function() {
let toController = function() {
var deferred = $q.defer();
firebase.database().ref('en').once('value') // get the array from the cloud database
.then(function(snapshot) { // take a snapshot
console.log(snapshot.val()); // read the values from the snapshot
return deferred.resolve(snapshot.val()); // this returns later
});
//return deferred.resolve(47) // this returns immeadiately
};
return {
toController: toController // why is this necessary?
}
});
如果你不想要这条线
返回{
toController:toController//为什么需要这样做?}
要在控制器中使用firebase调用的结果,factory方法需要返回承诺:
app.factory('asyncFactory', function($q) {
return {
toController: toController
};
function toController() {
var es6promise = firebase.database().ref('en').once('value');
var qPromise = $q.when(es6promise)
.then(function(snapshot) { // take a snapshot
console.log(snapshot.val()); // read the values from the snapshot
return snapshot.val(); // this returns later
});
return qPromise;
};
});
因为firebase.once
方法返回一个ES6承诺,所以需要通过将该承诺转换为带有的承诺,将其引入AngularJS框架。只有在AngularJS执行上下文中应用的操作才会受益于AngularJS数据绑定、异常处理、属性监视等
在控制器中,使用从服务器返回后提取数据:
var qPromise = asyncFactory.toController();
qPromise.then(function(data) {
console.log(data)
$scope.words = data;
});
工厂函数立即返回一个承诺。当数据从服务器到达时,数据将被放置在
$scope
promise不会去任何地方,因为您返回的不是它,而是47。阅读关于“我是否需要toController:toController行”,嗯,不需要,但是您的服务将根本没有方法,并且将非常无用。我的控制器正在从工厂返回“未定义”,即,它没有等待异步响应。但是谢谢你回答我的第二个问题!
var qPromise = asyncFactory.toController();
qPromise.then(function(data) {
console.log(data)
$scope.words = data;
});