AngularJS 提供了一個類似jquery的$.ajax的對象,用於異步請求。
在AngularJS中對異步操作是推崇至極的,所以$http的操作都是異步的不像jquery.ajax裏還提供了async參數。
對於官網的$http對象的總結和使用。
用法:
$http(config);
參數:
config (常用的參數標紅,翻譯了一下)
config | object |
Object describing the request to be made and how it should be processed. The object has following properties:
|
返回: 一個httpPromise對象(一般只用data和status)
HttpPromise |
Returns a promise object with the standard
|
方法:
get(url, [config]); 快捷的方法來執行GET請求。
post(url, data, [config]); 快捷的方法來執行POST請求。
put(url, data, [config]);
patch(url, data, [config]);
jsonp(url, [config]);
head(url, [config]);
delete(url, [config]);
我自己的使用例子(使用promise解決回調地獄問題)
var deferred = $q.defer();
$http({
cache: false,
method: 'GET',
url: Constants.baseURL + '/loginj',
params: params,
headers: {'X-Auth-Token': $window.token}
}).then(function(res) {
if (200 === res.status && res.data.LoginResponse.success) {
if (!Array.isArray(res.data.LoginResponse.settings.account)) {
res.data.LoginResponse.settings.account = [res.data.LoginResponse.settings.account];
}
CurrentUser.id = res.data.LoginResponse.settings.id;
deferred.resolve(res.data.LoginResponse.settings);
} else {
deferred.reject("failed to fetch login data");
}
}, function(error) {
deferred.reject(error.status+" "+error.statusText);
});
return deferred.promise;
官網地址:https://docs.angularjs.org/api/ng/service/$http (需要翻牆)
參考文章:http://zhaoyanblog.com/archives/99.html