我正在尝试使用 csvtojson node module从 csv 文件读取内容,以便我可以在 html View 中显示它。
下面我按照 csvtojson 页面上提供的示例进行操作。我成功读取并记录了 csv 文件的内容,但我无法弄清楚如何在正确的时间将内容传递到我的 Controller ,以便我可以在我的 View 中显示它们。目前,//public api
下的代码是在 csv 解析完成之前返回的。因此,结果以 ""
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
}
})
这是我的 Controller :
angular.module('piApp').controller('homeController', ['$scope', 'dataRetrievalService', function ($scope, dataRetrievalService) {
$scope.result = dataRetrievalService.result;
}]);
如何将从 csv 读取的内容显示在我的 html View 中?
<body ng-app="piApp">
{{result}}
</body>
非常感谢您抽出宝贵的时间。如果您需要更多信息或者我不清楚,请告诉我。
最佳答案
给getContents
一个回调函数,一旦完成就执行:
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);
}
然后在 Controller 中调用它:
dataRetrievalService.getContents(function(contents) {
$scope.result = contents;
});
关于javascript - 解析完成后如何将内容从服务传递到 Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31837062/