基本語法:
$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