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

 蒋军利 发布于 2023-02-13 03:04

我在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相关的问题上犯了一个错误.你能指点一下这个电话的正确方法吗?非常感谢!

2 个回答
  • 我建议你使用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;
      }
    });
    

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

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

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

    2023-02-13 03:22 回答
  • 首先,你的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;
        });
    });
    

    现在,$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服务来处理您使用config()设置的标头$httpProvider.查看$ http文档以获取示例.

    2023-02-13 03:24 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有