【问题标题】:How to pass content to controller from service after it is done being parsed?解析完成后如何将内容从服务传递给控制器​​?
【发布时间】:2015-08-05 15:43:48
【问题描述】:

我正在尝试使用 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>

非常感谢您的宝贵时间。如果您需要更多信息或者我不清楚,请告诉我。

【问题讨论】:

    标签: javascript angularjs node.js csv callback


    【解决方案1】:

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

    【讨论】:

    • 非常感谢您的帮助!我现在正在阅读回调。如果我将解析逻辑移动到另一个服务然后传递给数据检索服务,我将如何将相同的数据获取到视图中?我发布了new question here。如果您有时间检查一下,您可能会知道答案。感谢您的宝贵时间,我真的很感激。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-12
    • 1970-01-01
    • 2014-05-09
    • 2017-03-23
    相关资源
    最近更新 更多