【问题标题】:Using ngCsv with an external API将 ngCsv 与外部 API 一起使用
【发布时间】:2016-01-01 08:19:30
【问题描述】:

所以我有一个外部 API,我正在尝试使用 JSONP 和 $resource 服务访问和提取其中的数据。我想要一个来自ngCsv 的按钮,它发出请求,然后在数据请求完成时将数组导出到 csv 文件。但是当我单击按钮时,它会保存一个空的 csv 文件,因为请求大约需要 11 秒才能完成。我想点击按钮,当数据准备好并完全接收后,导出 csv 文件。

这是我的 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"});
  }
}])

这是我的 extract.html 路由。

 <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>

谢谢

【问题讨论】:

    标签: javascript angularjs angular-resource


    【解决方案1】:

    当您使用 $resource 时,它​​会返回一个承诺。所以你需要捕获返回值并返回到你的控制器函数,如下所示

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

    【讨论】:

      【解决方案2】:

      编辑: 基本上有人在我之前说过同样的话,但我会把它留在这里以防万一它对任何人有帮助:)

      如果您想在请求得到解决后采取行动,那么使用 Promise 是一个完美的案例。 让您的 apiExtractService.apiExtract 方法返回一个承诺并利用它。例如:

      function apiExtract(){
          var deferred = $q.defer();
          $http("get", "sampleUrl", optionalData)
              .success(function (response) {
                  deferred.resolve(response);
              })
              .error(function (err) {
                  deferred.reject(err);
              });
          return deferred.promise;
      }
      

      在你的控制器中:

      .controller('extractController',['$scope','apiExtractService',function ($scope,apiExtractService) {
        $scope.extract = function () {
          apiExtractService.apiExtract()
          .then(function(response){
           return response;
           }, function(err){
           console.log("something went wrong");
           });
        }
      

      【讨论】:

      • $resource 已经使用了 Promise!无需重新发明轮子
      • 我应该在哪里添加函数 apiExtract() ?在我的服务中?
      • 是的,apiExtract 是一个返回承诺的示例函数。您使用的 $resource 功能已经使用了@NickNasirpour 提到的承诺,这意味着您可以继续使用它,不需要我使用的 $http 服务,只是我习惯了它并且从未使用过 $resource 所以我提供了示例用我更舒服的东西:)
      【解决方案3】:

      您在 apiExtract 函数中返回了一个 $resource,该函数使用了 Promise。您应该返回实际内容,而不是将 promise 返回到 extract 函数,这可以使用 angularJS 的 $resource.$promise 属性来完成。

      $scope.extract = function() {
          apiExtractService.apiExtract().$promise.then(function(extractedData){
              return extractedData;
          });
      };
      

      【讨论】:

      • 感谢您的回答,但不知何故它不起作用!我不知道为什么!我正在使用角度 v1.4.8!你怎么看?
      • 你能告诉我你的 apiExtract 函数返回什么吗?
      • 是的,API 应该返回的 JSON
      【解决方案4】:

      我也有同样的问题。即使使用了承诺,我也得到了一个空文件。我能够通过传入数组而不是整个 API 响应 JSON 来解决它。

      API 响应是

      {
          "responseStatus": "001",
              "orderList":
          [{
              "id": 33, "status": null, "lastUpdatedDate": null, "lastUpdatedUser": null,
              "orderId": 1469830, "amount": 96, "discount": 6, "isPaid": "Y"
          }]
      }
      

      在控制器中

          .controller('extractController', ['$scope', 'apiExtractService', function ($scope, apiExtractService) {
          $scope.extract = function () {
              apiExtractService.apiExtract()
                  .then(function (response) {
                      //You have to return an array not full JSON
                      return response.orderList;
                  }, function (err) {
                      console.log("something went wrong");
                  });
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2020-09-21
        • 1970-01-01
        • 1970-01-01
        • 2016-10-22
        • 2010-11-27
        • 2023-03-31
        • 2019-12-06
        • 2016-01-30
        相关资源
        最近更新 更多