Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs http.get failure (but I see the data was returned)

I'm walking thru the Angularjs phones tutorial and want to get the phones JSON from a remote server.

$http.get('http://myserver.com/phones.json').success(function(data) {
    $scope.phones = data;
});

This failed due to CORS, I was sending an OPTIONS not a GET request, so I added this first line to the controller

delete $http.defaults.headers.common['X-Requested-With'];    

I can see now in Charles that a GET not OPTIONS request is being made to myserver.com, and that the phones JSON is in the response. But the http.get is still failing with status 0 and 'data' is null.

Not sure what to try next. Any insights appreciated.

like image 432
kurt steele Avatar asked Sep 02 '13 02:09

kurt steele


People also ask

What is HTTP get in AngularJS?

AngularJS automatically injects $scope parameter at runtime. The $http. get() method returns HttpPromise which includes methods like success() and error(). The success() method registers a callback method which is called when a request completes successfully.

Which object does the HTTP GET () function return?

HttpClient.get() returns response datalink HttpClient.get() returns the body of the response as an untyped JSON object by default.

How do we pass data and get data using HTTP in angular?

Use the HttpClient.get() method to fetch data from a server. The asynchronous method sends an HTTP request, and returns an Observable that emits the requested data when the response is received. The return type varies based on the observe and responseType values that you pass to the call.

How would you write code to modify the response from an HTTP GET?

catch( (error: Response) => { return Observable. throw(error); } );


1 Answers

It should not be making an OPTIONS request for a GET, so that sounds right. I think what you want to do is:

$http.get('http://myserver.com/phones.json').then(function(data) {
  $scope.phones = data;
}, function(err) { alert('Oh no! An error!'});

I think you want to use then(), which takes two functions as arguments — the first for success, and the second for error. $http.get() returns a promise which is acted upon by then().

Also, you probably want to use $resource instead of $http. It provides a higher level of abstraction, and allows for a more reusable style, http://docs.angularjs.org/api/ngResource.$resource

EDIT:

Check out the angular debug tool here. It shows you what is available in scopes, and shows performance data.

like image 132
Stuart Nelson Avatar answered Oct 03 '22 00:10

Stuart Nelson