基本语法:
$http.get('url',{}).success(function(data,status,headers,config){
}).error(function(data,status,headers,config){
})
$http.get接受两个参数:
1. url: 请求的路径
2. json对象: 请求参数配置,如 {params:{id:5}}
这样得到的实际路径就是url?id=5
$http.get返回的对象有两个回调方法:
1. success: 请求成功的回调
2. error: 请求失败的回调
这两个方法都有四个参数:
①data: 返回的数据(或错误)
②status: 响应的状态码
③headers: 这样一个函数,具体是什么暂时不详
function (name) { if (!headersObj) headersObj = parseHeaders(headers); if (name) { return headersObj[lowercase(name)] || null; } return headersObj; }
④congfig: 请求的配置对象
{ method: "GET", url: "/api/user",
params: {id:5}
}
下面看实例:
我们将请求得到的数据放入span标签内:
html:
<!DOCTYPE html> <html ng-app = 'HttpGet'> <head> <title>18.1 $http.get方法</title> <meta charset="utf-8"> <script src="angular.js"></script> <script src="script.js"></script> </head> <body> <div ng-controller = "dataController"> <span>{{data}}</span> </div> </body>
js:
var httpGet = angular.module('HttpGet',[]); httpGet.factory('getData',function($http,$q){ return function(){ var defer = $q.defer(); $http.get('/api/user').success(function(data,status,headers,congfig){ //console.log(status); //console.log(headers); //console.log(congfig); defer.resolve(data); }).error(function(data,status,headers,congfig){ defer.reject(data); }); return defer.promise } }); httpGet.controller('dataController',function($scope,getData){ $scope.data = getData() });
*注意以下方式是错误的:
因为data是异步返回的,必须使用$q的promise
var httpGet = angular.module('HttpGet',[]); httpGet.factory('getData',function($http,$q){ return function(){ var newdata = ''; $http.get('/api/user').success(function(data,status,headers,congfig){ newdata = data; }).error(function(data,status,headers,congfig){ newdata = data; }); return newdata } }); httpGet.controller('dataController',function($scope,getData){ $scope.data = getData() });
后端node代码:
var express = require('express'); var app = express(); app.use(express.static(__dirname+'')); var data = 'angularjs中的$http.get'; app.get('/api/user',function(req,res){ res.send(data) }); app.listen(3000);
完整代码地址: https://github.com/OOP-Code-Bunny/angular/tree/master/OREILLY/18.1%20%24http.get