Search code examples
javascriptangularjsjson

Angular $http response returns null when print in console but successfully requested


I have a local webservice developed with Spring, everything works fine (using browser or Postman), but when I try a simple GET method with Angular/Ionic it returns null in the response.

But when I look in the Net tab on Firebox console I see that the request was successfully made and returned the real JSON which is expected to return.

$http.get('http://localhost:8081/jungery/card/getCard/1').success(function(response) {
  console.log('Response:', response); // response is null
}).error(function(data, status, headers, config) {
  console.log('Error:', data);
});

Network tab on Firefox: enter image description here

When debugging on the server side I can confirm that the method on the webservice was really called.

@RequestMapping(value = "/getCard/{id}", method = { RequestMethod.GET, RequestMethod.OPTIONS }, headers = "Accept=application/json")
public Card getCardById(@PathVariable int id) {
    Card item = cardService.getCard(id);
    if (item == null) {
        item = new Card();
        item.setId(0L);
    }
    return item;
}

So, my question is: What am I missing here? I had done this before and never had such a strange behavior like this.


Solution

  • If you ensured that your webservice works ok, it's probably client's fault.

    Try "then" instead of "success".

    $http.get('http://localhost:8081/jungery/card/getCard/1').then(function(response) {
        console.log('Response:', response);
    }, function(data, status, headers, config) {
        console.log('Error:', data);
    });
    

    You can read more why this approach is preferred here: http://www.codelord.net/2015/05/25/dont-use-$https-success/ Also when consuming REST services with AngularJS you may consider using Restangular: https://github.com/mgonto/restangular