如何正确使用AngularJS中的HTTP.GET?具体来说,对于外部API调用?

Ana*_*Ram 38 javascript get http cors angularjs

我在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();
});
Run Code Online (Sandbox Code Playgroud)

但是,我认为我可能在与CORS相关的问题上犯了一个错误.你能指点一下这个电话的正确方法吗?非常感谢!

Kev*_*one 79

首先,你的success()处理程序只返回数据,但是它没有返回给调用者,getData()因为它已经在回调中了. $http是一个返回a的异步调用$promise,因此您必须在数据可用时注册回调.

我建议在AngularJS中查找Promises和$ q库,因为它们是传递服务之间异步调用的最佳方式.

为简单起见,这里是使用调用控制器提供的函数回调重写的相同代码:

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;
    });
});
Run Code Online (Sandbox Code Playgroud)

现在,$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;
    });
});
Run Code Online (Sandbox Code Playgroud)

最后,有更好的方法来配置$http服务来处理您使用config()设置的标头$httpProvider.查看$ http文档以获取示例.

  • 我使用`.then()`这是promise接口,它基本上与`.success()`相同但可链接..success/.error基本上不赞成承诺 (3认同)

Emi*_*uez 9

我建议你使用Promise

myApp.service('dataService', function($http,$q) {

  delete $http.defaults.headers.common['X-Requested-With'];
  this.getData = function() {
     deferred = $q.defer();
     $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, we can resolve promise and we can access it in controller
         deferred.resolve();
     }).error(function(){
          alert("error");
          //let the function caller know the error
          deferred.reject(error);
     });
     return deferred.promise;
  }
});
Run Code Online (Sandbox Code Playgroud)

所以在你的控制器中你可以使用这个方法

myApp.controller('AngularJSCtrl', function($scope, dataService) {
    $scope.data = null;
    dataService.getData().then(function(response) {
        $scope.data = response;
    });
});
Run Code Online (Sandbox Code Playgroud)

promise是angularjs的强大功能,如果你想避免嵌套回调,它很方便.

  • $ http已经返回一个承诺.在另一个承诺中包装$ http是多余的. (8认同)