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

我的未来我决定 提交于 2020-01-17 05:48:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!