AngularJS 中 异步请求$http 对象的使用
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
版权声明:本文为博主原创文章,未经博主允许不得转载。