我在 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();
});
但是,我认为我可能在 CORS 相关问题上犯了错误。你能告诉我调用这个电话的正确方法吗?非常感谢!
最佳答案
首先,您的 success()
处理程序只返回数据,但不会返回给 getData()
的调用者,因为它已经在回调中。 $http
是一个返回 $promise
的异步调用,因此您必须为数据可用时注册一个回调。
我建议查找 Promises 和 $q library在 AngularJS 中,因为它们是在服务之间传递异步调用的最佳方式。
为简单起见,下面是使用调用 Controller 提供的函数回调重写的相同代码:
var myApp = angular.module('myApp',[]);
myApp.service('dataService', function($http) {
delete $http.defaults.headers.common['X-Requested-With'];
this.getData = function(callbackFunc) {
$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){
// With the data succesfully returned, call our callback
callbackFunc(data);
}).error(function(){
alert("error");
});
}
});
myApp.controller('AngularJSCtrl', function($scope, dataService) {
$scope.data = null;
dataService.getData(function(dataResponse) {
$scope.data = dataResponse;
});
});
现在,$http
实际上已经返回了一个 $promise,因此可以重写:
var myApp = angular.module('myApp',[]);
myApp.service('dataService', function($http) {
delete $http.defaults.headers.common['X-Requested-With'];
this.getData = function() {
// $http() returns a $promise that we can add handlers with .then()
return $http({
method: 'GET',
url: 'https://www.example.com/api/v1/page',
params: 'limit=10, sort_by=created:desc',
headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
});
}
});
myApp.controller('AngularJSCtrl', function($scope, dataService) {
$scope.data = null;
dataService.getData().then(function(dataResponse) {
$scope.data = dataResponse;
});
});
最后,还有更好的方法来配置 $http
服务来为您处理 header ,使用 config()
设置 $httpProvider
.查看$http documentation例如。
关于javascript - 如何在 AngularJS 中正确使用 HTTP.GET?具体来说,对于外部 API 调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20369377/