栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在AngularJS中正确使用HTTP.GET?具体来说,是否需要外部API调用?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在AngularJS中正确使用HTTP.GET?具体来说,是否需要外部API调用?

首先,您的

success()
处理程序仅返回数据,但
getData()
由于已在回调中,因此不会返回给调用方。
$http
是一个返回的异步调用
$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文档
以获取示例。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/660406.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号