I have a service that uses a callback function to pass content to a controller:
angular.module(\'piApp\').service(\"dataRetrievalService\", function () {
fu
This is good idea to separate loading and parsing routines. However, instead of callback it's more convenient to use promises. This is how services could look like in this case:
angular.module('piApp').service("csvService", function($q) {
// public methods
function getCsvAsJSON() {
var deferred = $q.defer();
var fs = require("fs");
var Converter = require("csvtojson").Converter;
var fileStream = fs.createReadStream("Contents/Product Groups/orderTest2.csv");
var converter = new Converter({constructResult: true});
converter.on("end_parsed", function(jsonObj) {
deferred.resolve(jsonObj);
});
fileStream.pipe(converter);
return deferred.promise;
}
return {
getCsvAsJSON: getCsvAsJSON
}
});
angular.module('piApp').service("dataRetrievalService", ['csvService', function(csvService) {
function getContents() {
return csvService.getCsvAsJSON();
}
return {
getContents: getContents
}
}]);
angular.module('piApp').controller('homeController', ['$scope', 'dataRetrievalService', function ($scope, dataRetrievalService) {
dataRetrievalService.getContents().then(function(contents) {
$scope.result = contents;
});
}]);