How to pass content from service to another service to controller with callbacks after it has been parsed?

前端 未结 1 932
北海茫月
北海茫月 2021-01-23 04:15

I have a service that uses a callback function to pass content to a controller:

  angular.module(\'piApp\').service(\"dataRetrievalService\", function () {

  fu         


        
相关标签:
1条回答
  • 2021-01-23 04:32

    This is good idea to separate loading and parsing routines. However, instead of callback it's more convenient to use promises. This is how services could look like in this case:

    angular.module('piApp').service("csvService", function($q) {
    
        // public methods
        function getCsvAsJSON() {
            var deferred = $q.defer();
            var fs = require("fs");
            var Converter = require("csvtojson").Converter;
            var fileStream = fs.createReadStream("Contents/Product Groups/orderTest2.csv");
            var converter = new Converter({constructResult: true});
            converter.on("end_parsed", function(jsonObj) {
                deferred.resolve(jsonObj);
            });
            fileStream.pipe(converter);
            return deferred.promise;
        }
    
        return {
            getCsvAsJSON: getCsvAsJSON
        }
    });
    
    angular.module('piApp').service("dataRetrievalService", ['csvService', function(csvService) {
    
        function getContents() {
            return csvService.getCsvAsJSON();
        }
    
        return {
            getContents: getContents
        }
    }]);
    
    angular.module('piApp').controller('homeController', ['$scope', 'dataRetrievalService', function ($scope, dataRetrievalService) {
    
        dataRetrievalService.getContents().then(function(contents) {
            $scope.result = contents;
        });
    
    }]);
    
    0 讨论(0)
提交回复
热议问题