Search code examples
javascriptangularjsangular-resource

Using ngCsv with an external API


So I have an external API which I'm trying to access and extract the data in it using JSONP and $resource service. I want to have a button from ngCsv which makes the request then when the data request completed exports the array to a csv file. but when I click the button it saves an empty csv file because the request takes about 11s to complete. I want to click the button and when the data was ready and received completely, export the csv file.

Here's my app.js

// Initializing Application
angular.module('angelApp',['ngRoute','ngResource','ngSanitize','ngCsv'])

.config(function ($locationProvider,$routeProvider) {
  $locationProvider
  .html5Mode({
    enabled: true,
    requireBase:false
  })
  .hashPrefix('!');
  $routeProvider
  .when('/',{
    templateUrl: 'displays/main.html',
    controller: 'mainController'
  })
  .when('/extract',{
    templateUrl: 'displays/extract.html',
    controller: 'extractController'
  })
  .when('/about',{
    templateUrl: 'displays/about.html',
  })
  .otherwise({redirectTo: '/'});
})

// Defining Controllers
// Main page Controller
.controller('mainController',['$scope',function ($scope) {
  $scope.home = "Home Page!"
}])

// Extract Page Controller
.controller('extractController',['$scope','apiExtractService',function ($scope,apiExtractService) {
  $scope.extract = function () {
    return extractedData = apiExtractService.apiExtract();
  }
}])

// Adding Services To the application
.service('apiExtractService',['$resource',function ($resource) {
  this.apiExtract = function () {
    var apiData = $resource("APIADDRESS",{callback: "JSON_CALLBACK"},{get:{method: "JSONP"}});
    return apiData.get({filter: "FILTER",access_token:"TOKEN"});
  }
}])

Here's my extract.html route.

 <div class="row">
  <div class="col-md-6 col-md-offset-3">
    <button type="button" ng-csv="extract()" filename="test.csv">Export</button>
  </div>
</div>

Thank you


Solution

  • As you are using $resource which returns a promise. So you need to catch the return value and return to your controller function as below

    // Extract Page Controller
     .controller('extractController',['$scope','apiExtractService',function ($scope,apiExtractService) {
    
         $scope.extract = function () {
           return apiExtractService.apiExtract().then(function(results){
                   return results;
                 });
         }
    
      }])