调用工厂函数会触发错误

Invocation of Factory function triggers error

本文关键字:错误 工厂 函数 调用      更新时间:2023-09-26

我有一个 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

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

有什么线索吗?

谢谢。

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

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