作者:李桂平2402851397 | 来源:互联网 | 2023-05-17 17:42
Ihaveaproblemwhencallingaservicecreatedusing.factoryinmycontroller.Thecodelookslike
I have a problem when calling a service created using .factory in my controller. The code looks like the following. Factory (app.js):
调用在我的控制器中使用.factory创建的服务时遇到问题。代码如下所示。工厂(app.js):
.factory('Database',function($http){
return {
getDatabase: function(){
var database = {};
$http.get('http://localhost:3001/lookup').
success(function(data){
database.companyInfo = data.info.companyInfo;
});
}).
error(function(data){
console.log('Error' + data);
});
return database;
}
};
})
Controller:
angular.module('webClientApp')
.controller('MainCtrl', function (Database,Features,$scope,$http) {
$scope.databaseString = [];
$scope.quarters = ['Q1','Q2','Q3','Q4'];
$scope.years = ['2004','2005','2006','2007','2008','2009','2010',
'2011','2012','2013','2014'];
$scope.features = Features.getFeatures();
$scope.database = Database.getDatabase();
console.log($scope.database);
Now when I inspect the element in Firebug I get the console.log($scope.database)
printed out before the GET statement result. $scope.database
is shown as an Object {}
with all the proprieties in place. However if I try to use console.log($scope.database.companyInfo)
I get an undefined
as result, while instead I should get that data.info.companyInfo' that I passed from the
Database` service (in this case an array).
现在,当我检查Firebug中的元素时,我得到了在GET语句结果之前打印出的console.log($ scope.database)。 $ scope.database显示为Object {},其中包含所有属性。但是,如果我尝试使用console.log($ scope.database.companyInfo),我得到一个未定义的结果,而我应该得到我从theDatabase`服务传递的data.info.companyInfo(在这种情况下是一个数组) 。
What is the problem here? Can someone help me? (If you need clarifications please let me know..)
这里有什么问题?有人能帮我吗? (如果您需要澄清,请告诉我..)
2 个解决方案
7
The $http.get() call is asynchronous and makes use of promise objects. So, based on the code you provided it seems most likely that you are outputting the $scope.database before the success method is run in the service.
$ http.get()调用是异步的,并使用promise对象。因此,根据您提供的代码,您很可能在服务中运行success方法之前输出$ scope.database。
I build all my service methods to pass in a success or failure function. This would be the service:
我构建了所有的服务方法来传递成功或失败的功能。这将是服务:
.factory('Database',function($http){
return {
getDatabase: function(onSuccuess,onFailure){
var database = {};
$http.get('http://localhost:3001/lookup').
success(onSuccess).
error(onFailure);
}
};
})
This would be the controller code:
这将是控制器代码:
angular.module('webClientApp')
.controller('MainCtrl', function (Database,Features,$scope,$http) {
$scope.databaseString = [];
$scope.quarters = ['Q1','Q2','Q3','Q4'];
$scope.years = ['2004','2005','2006','2007','2008','2009','2010',
'2011','2012','2013','2014'];
$scope.features = Features.getFeatures();
Database.getDatabase(successFunction,failureFunction);
successFunction = function(data){
$scope.database = data.info.companyInfo;
console.log($scope.database);
});
failureFunction = function(data){
console.log('Error' + data);
}