我完全无法尝试在我的 Controller 中实例化一个工厂。无论我做什么,我的工厂 ('FBRetrieve') 似乎都未定义。它一定很简单,但似乎无法通过 S/O search/google/angulardocs 找到解决方案。
应用程序.js
var legalmvc = angular.module('legalmvc', ['ngRoute','FireBaseService']);
工厂.js
angular.module("FireBaseService", []).factory('FBRetrieve', function(){
var biblioData = new Object();
biblioData.getData = function(type){
var biblioRef = new Firebase('https://legalcitator.firebaseio.com/'+type);
biblioRef.on('value', function(data) {
if (data.val() === null) {
console.log("ERROR");
return;
}
console.log(data.val());
biblioData = data.val();
});
return biblioData;
};
});
在 Controller 中我用这样的东西实例化:
legalmvc.controller('FormCtrl',["$scope","FBRetrieve", function ($scope, FBRetrieve) {
$scope.FBRetrieve = FBRetrieve.getData('case');
.....
最佳答案
getData
是异步操作,这意味着当您尝试返回它时,响应还没有可用。相反,您应该使用延迟模式的回调(在这种情况下更自然):
biblioData.getData = function(type) {
var biblioRef = new Firebase('https://legalcitator.firebaseio.com/'+type),
deferred = $q.defer(); // remember to inject $q service into factory
biblioRef.on('value', function(data) {
if (data.val() === null) {
deferred.reject('ERROR');
}
deferred.resolve(data.val());
});
return deferred.promise;
};
然后你会在 Controller 中使用它:
FBRetrieve.getData('case').then(function(data) {
$scope.FBRetrieve = data;
}, function() {
// handle error
});
同时了解这个常见的 problem and solution .
关于javascript - Angular 依赖注入(inject) - 无法实例化工厂/未定义的工厂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24723152/