user1718064 user1718064 - 5 months ago 10
AngularJS Question

Calling service for factory in controller

I have a problem when calling a service created using .factory in my controller.
The code looks like the following.
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).

What is the problem here? Can someone help me?
(If you need clarifications please let me know..)

Answer

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.

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