I have a function to access mongodb using mongoose, the database call works and appears in the console but it doesn't return that array as it should. Can't figure out why.
exports.getPrices = function() {
return Price.find().exec(function (err, docs) {
if (err) {
return err;
}
console.log(docs);
return docs;
});
};
the call from the service
angular.module('core')
.factory('Machineprice', [ '$http',
function($http) {
return {
getPrices:function(){
return $http.get('/getPrices')
}
};
}
]
);
the controller
angular.module('core').controller('MachinePricingController', ['$scope','Machineprice',
function($scope, Machineprice) {
$scope.prices = Machineprice.getPrices();
console.log($scope.prices);
}
]);
It's not working because the getPrices()
runs asynchronously which means it doesn't return the result instantly. That function returns a promise which means the result has to be dealt with in a callback function.
Quote from AngularJS site:
The $http service is a function which takes a single argument — a configuration object — that is used to generate an HTTP request and returns a promise.
To make it work, you have to change the code of your controller.
angular.module('core').controller('MachinePricingController', ['$scope', 'Machineprice',
function ($scope, Machineprice) {
Machineprice.getPrices().then(function (response) {
$scope.prices = response.data;
console.log($scope.prices);
});
}]);