I have the following code in the controller.js,
var myApp = angular.module('myApp',[]);
myApp.service('dataService', function($http) {
delete $http.defaults.headers.common['X-Requested-With'];
this.getData = function() {
$http({
method: 'GET',
url: 'https://www.example.com/api/v1/page',
params: 'limit=10, sort_by=created:desc',
headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
}).success(function(data){
return data
}).error(function(){
alert("error");
});
}
});
myApp.controller('AngularJSCtrl', function($scope, dataService) {
$scope.data = dataService.getData();
});
But, I think I m probably making a mistake with CORS related issue. Can you please point me to the correct way to make this call? Thanks much!
Try this
Just setting useXDomain = true is not enough. AJAX request are also send with the X-Requested-With header, which indicate them as being AJAX. Removing the header is necessary, so the server is not rejecting the incoming request.
Using Google Finance as an example to retrieve the ticker's last close price and the updated date & time. You may visit YouTiming.com for the run-time execution.
The service:
The controller:
The HTML:
At the top of YouTiming.com home page, I have placed the notes for how to disable the CORS policy on Chrome and Safari.
First, your
success()
handler just returns the data, but that's not returned to the caller ofgetData()
since it's already in a callback.$http
is an asynchronous call that returns a$promise
, so you have to register a callback for when the data is available.I'd recommend looking up Promises and the $q library in AngularJS since they're the best way to pass around asynchronous calls between services.
For simplicity, here's your same code re-written with a function callback provided by the calling controller:
Now,
$http
actually already returns a $promise, so this can be re-written:Finally, there's better ways to configure the
$http
service to handle the headers for you usingconfig()
to setup the$httpProvider
. Checkout the $http documentation for examples.No need to promise with $http, i use it just with two returns :
In controller
So you need to use what we call promise. Read how angular handles it here, https://docs.angularjs.org/api/ng/service/$q. Turns our $http support promises inherently so in your case we'll do something like this,
I suggest you use Promise
so In your controller you can use the method
promises are powerful feature of angularjs and it is convenient special if you want to avoid nesting callbacks.