Angular 中的 $http 简单解释
Angular 中的 $http 简单解释
引言
$http
服务是一个函数,它接受一个参数——一个配置对象——用于生成 HTTP 请求,并返回一个 Promise(https://docs.angularjs.org/api/ng/service/$http)。
本文将通过一个简单的例子来说明 AngularJS 的 $http
服务。该示例将演示检查 IP 地址,调用 URL http://ip.jsontest.com/,该 URL 将以 JSON 格式返回您的 IP 地址。
Using the Code
下面是一个简单的 HTML 文件,其中包含表达式 {{myIP}},IP 地址将在此处渲染。
Index.html
<html>
<head>
<title>$http fun</title>
</head>
<body ng-app="app">
<div ng-controller="TestCtrl">
{{myIP}}
</div>
<script type="text/javascript"
src="https://code.angularjs.org/1.5.0/angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
下面是演示 $http
服务的 AngularJS 代码。
app.js
var app = angular.module('app', []);
app.controller("TestCtrl", function($scope, $http) {
$http({
method: 'GET',
url: 'http://ip.jsontest.com/'
})
.then(function(response) {
$scope.myIP= response.data.ip;
})
})
$http
也可以以简写形式调用,如下所示。我们将采用这种方法进行其余的示例。
app.js 演示使用 $http 的简写方式
var app = angular.module('app',[]);
app.controller("TestCtrl",function($scope,$http){
$http.get('http://ip.jsontest.com/')
.then(function(response){
$scope.myIP= response.data.ip;
})
})
输出
上面的示例显示了 AngularJS 中 $http
服务的一个简单用法。$http
被注入到控制器中。$http.get
使用提供的 URL 调用。如上所述,$http
返回一个 Promise 对象。Promise 对象有两个函数,then
和 catch
。当 Promise 成功时调用 then
函数,当 Promise 发生错误时调用 catch
函数。
在上面的示例中,then
函数的第一个参数在成功时被调用,返回响应对象。响应对象如下所示
{"data":{"ip":"103.255.227.108"},"status":200,"config":{"method":"GET","transformRequest":[null],
"transformResponse":[null],"url":"http://ip.jsontest.com/","headers":{"Accept":"application/json,
text/plain, */*"}},"statusText":"OK"}
由于我们正在尝试检索 IP 地址,我们使用 $scope.myIP= response.data.ip
获取它。
处理异常
为了处理抛出异常的情况,例如访问 URL 时出现 404 错误,then
函数可以有一个额外的参数来处理它。
app.js 演示使用 then 中的附加参数进行异常处理
var app = angular.module('app',[]);
app.controller("TestCtrl",function($scope,$http){
$http.get('http://google.co.in/abcd')
.then(function(response){
$scope.myIP= response;
}, function(error){
$scope.myIP= error.status;
})
})
注意:提供的 URL 为 'http://google.co.in/abcd',它将返回 404 错误。
catch
函数也可以用来处理异常。
app.js 演示使用 Catch 进行异常处理
var app = angular.module('app', []);
app.controller("TestCtrl", function($scope, $http) {
$http.get('http://google.com/abcd')
.then(function(response) {
$scope.myIP = response.data.ip;
})
.catch(function(error) {
$scope.myIP = error.status;
})
})