解析完成后如何将内容从服务传递给控制器​​?

How to pass content to controller from service after it is done being parsed?

我正在尝试使用 csvtojson node module 从 csv 文件中读取内容,以便在 html 视图中显示它。

下面我按照 csvtojson 页面上提供的示例进行操作。我成功读取并记录了 csv 文件的内容,但我不知道如何在正确的时间将内容传递到我的控制器,以便我可以在我的视图中显示它们。当前,// 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
}
})

这是我的控制器:

angular.module('piApp').controller('homeController', ['$scope', 'dataRetrievalService', function ($scope, dataRetrievalService) {

$scope.result = dataRetrievalService.result;

}]);

如何让从 csv 读取的内容显示在我的 html 视图中?

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

然后在你的控制器中调用它:

dataRetrievalService.getContents(function(contents) {
    $scope.result = contents;
});