ChanX
ChanX

Reputation: 372

Nothing returned When doing $http Promise in Angular

I am trying to make a $http.jsonp call but the promise service is returning blank without data:

Below is my Js code

diary.factory('SongInfo', function ($http,$q) {
return {

    //Return All Available Songs from the Database
    getAllSongs : function () {
        var defer = $q.defer();

        $http.jsonp('http://fashion.c-research.in/api/?getsongs&name=JSON_CALLBACK')
            .then(function (res){
                defer.resolve(res.data);
            })

        return defer.promise;

    },

    //Get Song using the particular ID
    getSongInfo : function (trackid) {
        var defer = $q.defer();

        $http.jsonp('http://fashion.c-research.in/api/?trackid='+trackid+'&name=JSON_CALLBACK')
            .success(function(res){
                defer.resolve(res);
            })
            .error(function (err){
                defer.reject(err);
            });

        return defer.promise;

    }
}
});

here is the Controller function:

diary.controller('PlayController', ['$scope', 'DeviceReady', 'SongInfo', function($scope, DeviceReady, SongInfo) {

        var promise = SongInfo.getAllSongs();

        promise.then(
            function (payload) {
                console.log(payload);
            }
        )

}]);

Nothing is being queried from the API.. Inned way to oreate

Upvotes: 0

Views: 230

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136194

You must always send callback parameter inside jsonp call url,

Use callback=JSON_CALLBACK instead of name=JSON_CALLBACK

Code

diary.factory('SongInfo', function($http, $q) {
    return {
        //Return All Available Songs from the Database
        getAllSongs: function() {
            var defer = $q.defer();
            $http.jsonp('http://fashion.c-research.in/api/?getsongs&callback=JSON_CALLBACK')
            .then(function(res) {
              defer.resolve(res.data);
            }, function(err) {
              defer.reject(err);
            });
            return defer.promise;
        },

        //Get Song using the particular ID
        getSongInfo: function(trackid) {
            var defer = $q.defer();
            $http.jsonp('http://fashion.c-research.in/api/?trackid=' + trackid + '&callback=JSON_CALLBACK')
            .success(function(res) {
              defer.resolve(res);
            })
            .error(function(err) {
              defer.reject(err);
            });
            return defer.promise;
        }
    }
});

Upvotes: 1

Related Questions