【发布时间】: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