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

2 Answers 2

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);
    });
}]);
Sign up to request clarification or add additional context in comments.

Comments

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

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.