Radu
Radu

Reputation: 1104

How to call external rest service from angularjs?



I am trying to call an external REST service from angular using $http service.
The thing is that I am stuck on the $http.get method, because everytime I call
the rest service i get an error with status = 0 and no information in the data parameter
of the error callback.

So far I've tried calling a local service runnig on port 5000 : $http.get('http://localhost:5000/ping') and this is supposed to return a json object with a property and a value. Another approach was calling http://api.flickr.com/services/rest/?method=flickr.test.echo&name=test in the hope of getting an answer. For both of them I get the same error: that I mentioned earlier.

The call is made from an angular controller that has injected the http service.

Thanks.

Upvotes: 1

Views: 6056

Answers (3)

Aibu
Aibu

Reputation: 401

As $http returns a Promise, you can use the .then() method to log your results when the promise is resolved, or log an error in case anything goes wrong:

$http.get('http://localhost:5000/ping')
    .then(function(returnedJson) {
        console.log(returnedJson.data);
    })
    .catch(console.error) // or $log.error if you are using $log from Angular

Please note that the clean JSON response is obtained by logging the .data property of the returnedJson object. As it is a Promise, it contains other information that are not relevant to consume the web service.

Also note that the web service you want to consume should also be in the same domain as your Angular app, otherwise you may incur into a Cross Domain error, unless the service allows usage from external websites by exposing a Cross Domain Policy.

(Find more info here: Can someone post a well formed crossdomain.xml sample?)

If that's the case, this post should be helpful:

jQuery AJAX cross domain

Hope this helps.

Upvotes: 0

Pritam Banerjee
Pritam Banerjee

Reputation: 18923

Make sure that you have passed the parameters correctly if there are any.
The general syntax should be like the following :

$http.get('../link/yourApplication/searchBySomeNumber?someNum='+$scope.someNum+'&asOfDate='+asOfDate+'&status=undefined') 
            .success(function(data, status, headers, config) {
                //your code
                console.log('Data return successful');
            })
            .error(function(data, status, headers, config) {
                $scope.status = status;
                alert('Info Error');
                console.log('Group Info Error');
            });

Upvotes: 0

ssoward
ssoward

Reputation: 540

Have you tried:

    $http({method: 'GET', url: 'someURL'}).
            success(function(data, status, headers, config) {
                //set view model or do something.

            }).
            error(function(data, status, headers, config) {

            });

Upvotes: 3

Related Questions