asafdav / ng-csv

Simple directive that turns arrays and objects into downloadable CSV files
MIT License
573 stars 215 forks source link

Problems with promise #100

Open dmelo opened 9 years ago

dmelo commented 9 years ago

I'm relatively new to AngularJS, so I might be doing a basic/noob mistake.

I'm using resource to load the CSV content that I want the user to download. The code goes like this:

$scope.exportCsv = function() {
    var request = $resource("http://localhost:8080/", {}, {
        query: {
            method: 'GET',
            headers: {'Content-Type': 'application/json'},
            params: {
                id: $scope.id
            }
        }
    }).query(function(data) {

        var ret = [];

        ret.push($scope.tableHeader());

        data._embedded.passage.forEach(function (value) {
            ret.push([
                value.id,
                value.name
            ]);
        });

        return ret;
    });

    return request.$promise;
};

On my html I have:

<button class="btn btn-success" ng-csv="exportCsv()" filename="list.csv">Exportar (CSV)</button>

If my exportCsv function returns just an array, it works just fine. However, trying to return the promise makes the it download an empty file.

The file (list.csv) only goes to download after the request to "http://localhost:8080" is complete. So I guess part of the way is right.

Is it a bug or am I missing something?

dmelo commented 9 years ago

I've just solved the isse. In my case, "http://localhost:8080" returns a JSON object. Not the array ng-csv expects. Moreover, the function I'm passing to "query" was not being executed by ng-csv.

The solution is to make a chain of promises:

var promise = request.$promise.then(data) {
    // ...
    // transfor data from an object the the kind of array ng-csv expects

    return ret;
});

And return this new promise on $scope.exportCsv.

I'm not sure if this is a basic thing. But I will try to make an example out of it and send a pr.