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.
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.
HttpClient.get() returns response datalink HttpClient.get() returns the body of the response as an untyped JSON object by default.
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.
catch( (error: Response) => { return Observable. throw(error); } );
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With