如何从角度中的$ http.json请求返回转换后的数据?

时间:2016-02-08 21:26:36

标签: javascript angularjs ajax xmlhttprequest jsonp

如何使用APIData.map返回APIdata而非默认成功$http.jsonp

LangDataService构造函数:

 languages.LangDataService = function($http, $q) {
   this.langDefer = $q.defer();
   this.isDataReady = this.langDefer.promise;
 };


languages.LangDataService.prototype.getApi = function() {
    return this.isDataReady = this.http_.jsonp(URL, {
        params: {}
      })
      .success(function(APIData) {
        return APIData.map(function(item){
              return item + 1; //just an example.
         });
      });
};

使用LandDataService的Ctrl:

languages.LanguageCtrl = function(langDataService) {
   languages.langDataService.isDataReady.then(function(data){
       console.log('whooo im a transformed dataset', data);
   });
}

2 个答案:

答案 0 :(得分:1)

someKeyspace函数中使用then代替success

答案 1 :(得分:1)

尝试以下版本: https://jsfiddle.net/L2ndft4w/

// define the module for our AngularJS application
var app = angular.module('App', []);

app.factory('LangDataService', function($q,$http) {

  return {
    getApi: function() {
      var defer= $q.defer();
      $http({
          url: 'https://mysafeinfo.com/api/data?list=zodiac&format=json&alias=nm=name',
          dataType: 'json',
          method: 'GET',
          data: '',
          headers: {
              "Content-Type": "application/json"
          }
      }).
      success(function (data) {

          defer.resolve(data.map(function(item){
            return item.name;
          }));
      })    
      return defer.promise;
    }  
  };
});

// invoke controller and retrieve data from $http service
app.controller('DataController', function ($scope, LangDataService) {
  LangDataService.getApi().then(function(data){
    $scope.data = JSON.stringify(data, null, 2);
  });
});

返回:

[
  "Aquarius",
  "Aries",
  "Cancer",
  "Capricorn",
  "Gemini",
  "Leo",
  "Libra",
  "Ophiuchus",
  "Pisces",
  "Sagittarius",
  "Scorpio",
  "Taurus",
  "Virgo"
]

虽然,因为$ http已经是一个承诺,可能有一个更短的方法来做到这一点......($q.when?)