1

// this is service where i m calling api
app.factory('users',['$http','$q', function($http , $q) {
 
       return {
        getUsers: function() {
         var deferred = $q.defer();
         var url = 'http://www.geognos.com/api/en/countries/info/all.jsonp?callback=JSONP_CALLBACK';
         
         $http.jsonp(url).success(function (data, status, headers, config) {
          console.log(data);
          deferred.resolve(data);
         }).
             error(function (data, status, headers, config) {
                //this always gets called
                console.log(status);
                deferred.reject(status);
            });
            return deferred.promise;

     } 
       }
       
}]);

//this is my controller where i calling getUsers();


app.controller('myCtrl', function($scope, users) {
        $scope.data = users.getUsers();

    })

while calling it gives me error

Uncaught ReferenceError: callback is not defined(anonymous function)

Plz give me proper solution so that i can see me api data in <div>. Thanks in advance

naveen
  • 53,448
  • 46
  • 161
  • 251
Puja Singh
  • 87
  • 2
  • 10

2 Answers2

1

$http already returns a promise. There is no need to form a promise of a promise. Try this:

app.factory('Users', ["$http", function($http){
    return {
        getUsers: function(url) {
            return $http({
                url: url,
                method: 'JSONP'
            });
        }
    };
}]);

Controller:

app.controller("MyCtrl", ["$scope", "Users", function($scope, Users) {
    $scope.data = [];
    Users.getUsers('http://www.geognos.com/api/en/countries/info/all.jsonp?callback=JSONP_CALLBACK').then(function(response){
        console.log(response.data);
        $scope.data = response.data;
    }).catch(function(response){
        console.log(response.statusText);
    });
}]);
Kyle
  • 5,407
  • 6
  • 32
  • 47
1

Here the scenario is a bit different as you have to declare a $window.callback function.

Code

var app = angular.module("demoApp", []);
app.factory('UserService', ['$http', function ($http, $q) {

    var getUsers = function () {
        var url = 'http://www.geognos.com/api/en/countries/info/all.jsonp?callback=callback';
        return $http.jsonp(url);
    };
    return {
        GetUsers: getUsers
    }

}]);
app.controller("demoController",
["$scope", "$window", "UserService",
    function ($scope, $window, UserService){
        UserService.GetUsers();
        $window.callback = function (response) {
            $scope.countries = response.Results;
        }
}]);

Plunkr: http://plnkr.co/edit/MFVpj1sMqJpcDg3ZwQFb?p=preview

naveen
  • 53,448
  • 46
  • 161
  • 251