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

时间:2015-08-05 15:43:49

标签: javascript angularjs node.js csv callback

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

下面我将按照csvtojson页面上提供的示例进行操作。我正在成功读取和记录csv文件的内容,但我无法弄清楚如何在正确的时间将内容传递给我的控制器,以便我可以在我的视图中显示它们。目前,在解析csv之前返回// public api下的代码。因此,结果传递的值为""

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>

非常感谢你的时间。如果您需要其他信息或我不清楚,请告诉我。

1 个答案:

答案 0 :(得分:2)

一旦完成,就给. clear . input str30 lbl lbl 1. "See/hear ACT: `Newspaper" 2. end . generate from = char(96) . generate lbl2 = subinstr(lbl,from,"",.) . list, clean noobs lbl from lbl2 See/hear ACT: `Newspaper ` See/hear ACT: Newspaper . 一个回调函数执行:

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