0

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

2 Answers 2

1

Use then instead of success in getApi function.

Sign up to request clarification or add additional context in comments.

1 Comment

For some reason when you put a then it wraps the data in a data key .. and I refused to read the errors and thought it was angular not working. Thanks.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.