【问题标题】:Invocation of Factory function triggers error调用工厂函数触发错误
【发布时间】:2016-01-14 08:18:18
【问题描述】:

我有一个 Angular 应用程序,其中通过工厂内的单个函数管理数据库访问。工厂声明为:

var MayApp = angular.module('MayApp'); 

MayApp.factory("DB_Services", [ "$http" , function($http) {

    var This_Factory = {} ;

    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

    This_Factory.Get_Data_from_DB_Internal = function (p_Request) {

        var http    = new XMLHttpRequest()  ;
        var url     = MyURL                 ;
        var params  = "data=" + p_Request   ;
        http.open("POST", url, true);

        //Send the proper header information along with the request
        http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

        http.onreadystatechange = function() {
            if(http.readyState == 4 && http.status == 200) {
                return http.responseText ;
            }
        }
        http.send(params);    
    }    

    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

    This_Factory.Get_Data_from_DB = function Get_Data_from_DB($scope, DB_Services) {
        var myDataPromise = DB_Services.Get_Data_from_DB_Internal("Dummy");
        myDataPromise.then(function(result) {
            return result ;
        });
    }
    return This_Factory ;
}]);

使用该服务的控制器如下所示:

MayApp.controller('MyController' , ['$scope' , 'DB_Services' , function( $scope , DB_Services) {

    $scope.Search_Lookups = function () {

        var l_Lookup_Type = document.getElementById("Lookup_Seed").value ;

        var l_Data = MyApp.DB_Services.Get_Data_from_DB(l_Lookup_Type);

        console.log ("Received response: " + l_Data) ;

        return l_Data ;

    }

} ]) ;

单击按钮时会调用函数Search_Lookups。生成的错误信息为:TypeError: Cannot read property 'Get_Data_from_DB' of undefined

我在这个工厂有issues,并通过在 index.html 文件中更改其包含位置(即<script src="Private_Libs/Factories/DB_Services.js"></script>)来解决。现在,我在加载页面时没有收到任何错误,但控制器仍然看不到 Get_Data_from_DB

有什么线索吗?

谢谢。

【问题讨论】:

  • 你自己做 XMLHttpRequest 有什么原因吗?

标签: javascript angularjs


【解决方案1】:

您已经以DB_Services 的名义将工厂注入到您的控制器中。当您想调用它时,您只需使用DB_Services,而不是MayApp.DB_Services,工厂不是您的应用程序的方法,它是您在注入时定义的控制器中的独立变量。

你处理请求的方式也是如此,我认为它不会起作用,你应该从工厂传回一个承诺,而不是你的承诺解决后检索到的值,因为你的控制器在之后立即将 l_data 分配给 undefined你调用工厂函数,并且不会等待工厂的承诺解决。

【讨论】:

  • 嘿@SinaGh!!!您对第一点的建议起到了作用。至于第二个……正在学习……谢谢你的快速修复。
  • @FDavidov 很高兴你把我的建议放在心上:)
  • 亲爱的@SinaGh,在过去的日子里,我了解到你的话应该始终被认真对待,虽然我缺乏很多知识,但我学得很快! :-)。顺便说一句,我也解决了第二点,所以现在我可以很好地访问数据库了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-07
  • 1970-01-01
  • 1970-01-01
  • 2018-09-15
相关资源
最近更新 更多