Matthew Harwood February 2016

How to return transformed data from a $http.json request in angular?

How can I return the APIData.map and not the default success APIdata using $http.jsonp?

LangDataService Constructor:

 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.
         });
      });
};

A Ctrl using LandDataService:

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

Answers


Viktor Kukurba February 2016

Use then instead of success in getApi function.


malix February 2016

Try a version of the following: 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);
  });
});

Returns:

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

Although, since $http is already a promise, there's probably a shorter way to do this... ($q.when?)

Post Status

Asked in February 2016
Viewed 3,370 times
Voted 4
Answered 2 times

Search




Leave an answer