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
AngularJS提供了一个$http服务,它类似于jQuery的$.ajax,专门用于异步请求。$http的所有操作默认都是异步的,不支持同步设置。主要方法包括GET、POST、PUT、PATCH、DELETE等。通过配置对象可以定制请求。使用$http服务可以避免回调地狱,通过promise进行链式调用。了解更多详情,可以查阅AngularJS官方文档。

5050

被折叠的 条评论
为什么被折叠?



