【问题标题】:Angular Dependency Injection -Can't Instantiate Factory/ Undefined FactoryAngular 依赖注入 - 无法实例化工厂/未定义工厂
【发布时间】:2014-07-13 13:24:52
【问题描述】:

试图在我的控制器中实例化一个工厂,我完全把自己难住了。无论我做什么,我的工厂('FBRetrieve')似乎都是未定义的。一定是很简单的事情,但似乎无法通过 S/O 搜索/google/angulardocs 找到解决方案。

app.js

var legalmvc = angular.module('legalmvc', ['ngRoute','FireBaseService']);

factory.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;

    };

});

在控制器中,我正在用类似这样的东西进行实例化:

legalmvc.controller('FormCtrl',["$scope","FBRetrieve", function ($scope, FBRetrieve) {

    $scope.FBRetrieve = FBRetrieve.getData('case');

..... 

【问题讨论】:

    标签: javascript angularjs firebase angularfire


    【解决方案1】:

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

    然后你会在控制器中使用它:

    FBRetrieve.getData('case').then(function(data) {
        $scope.FBRetrieve = data;
    }, function() {
        // handle error
    });
    

    还可以了解这个常见的problem and solution

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多