问题
I am trying to use the csvtojson node module to read content from a csv file so that I can display it in my html view.
Below I follow the example provided on the csvtojson page. I am successfully reading and logging the contents of the csv file, but I cannot figure out how to pass the contents to my controller at the right time so that I can display them in my view. Currently, the code under // public api is returned before the csv is finished being parsed. Consequently, result is passed with a value of ""
angular.module('piApp').service("dataRetrievalService", function () {
// public methods
function getContents() {
//Converter Class
var fs = require("fs");
var Converter = require("csvtojson").Converter;
var fileStream = fs.createReadStream("order.csv");
//new converter instance
var converter = new Converter({ constructResult: true });
//end_parsed will be emitted once parsing finished
converter.on("end_parsed", function (jsonObj) {
console.log(jsonObj); //here is your result json object
getResult(jsonObj)
});
//read from file
fileStream.pipe(converter);
}
this.result = "";
function getResult(jsonObj) {
result = jsonObj;
}
// public api
return {
getContents: getContents,
result: this.result
}
})
Here's my controller:
angular.module('piApp').controller('homeController', ['$scope', 'dataRetrievalService', function ($scope, dataRetrievalService) {
$scope.result = dataRetrievalService.result;
}]);
How would I get the content read from the csv to display in my html view?
<body ng-app="piApp">
{{result}}
</body>
Thank you very much for your time. Let me know if you need additional information or if I am being unclear.
回答1:
Give getContents a callback function execute once it's done:
function getContents(callback) {
//Converter Class
var fs = require("fs");
var Converter = require("csvtojson").Converter;
var fileStream = fs.createReadStream("order.csv");
//new converter instance
var converter = new Converter({ constructResult: true });
//end_parsed will be emitted once parsing finished
converter.on("end_parsed", function (jsonObj) {
console.log(jsonObj); //here is your result json object
//getResult(jsonObj)
callback(jsonObj);
});
//read from file
fileStream.pipe(converter);
}
Then call it in your controller:
dataRetrievalService.getContents(function(contents) {
$scope.result = contents;
});
来源:https://stackoverflow.com/questions/31837062/how-to-pass-content-to-controller-from-service-after-it-is-done-being-parsed