Angularjs的$http then方法的success和then有什么区别

Posts - 5,
Articles - 0,
Comments - 5
23:45 by 小沈_syt, ... 阅读,
  在angularJS中与远程HTTP服务器交互时会用一个非常关键的服务-$http。
 $http是angular中的一个核心服务,利用浏览器的xmlhttprequest或者via JSONP对象与远程HTTP服务器进行交互。
 $http的使用方式和jquery提供的$.ajax操作比较相同,均支持多种method的请求,get、post、put、delete等。
 $http的各种方式的请求更趋近于rest风格。
& &在controller中可通过与$scope同样的方式获取$http对象,e.g. function controller($scope,$http){}
  下面进行$http服务的使用说明,调用如下:
$http(config).success(function(data,status,headers,config){}).error(function(data,status,headers,config){});
config为一个JSON对象,其中主要包含该请求的url、data、method等,如{url:"login.do",method:"post",data:{name:"12346",pwd:"123"}}。
method &{String} 请求方式e.g. "GET"."POST"
url {String} 请求的URL地址
params {key,value} 请求参数,将在URL上被拼接成?key=value
data {key,value} 数据,将被放入请求内发送至服务器
cache {boolean} 若为true,在http GET请求时采用默认的$http cache,否则使用$cacheFactory的实例
timeout {number} 设置超时时间
  2、success为请求成功后的回调函数,error为请求失败后的回调函数,这里主要是对返回的四个参数进行说明。
data 响应体
status 相应的状态值
headers 获取getter的函数
config 请求中的config对象,同上第1点 & &
  为了方便大家与HTTP服务器进行交互,angularJS提供了各个请求方式下方法。
      $http.put/post(url,data,config) url、name必填,config可选
      $http.get/delete/jsonp/head(url,confid)&url必填,config可选
  url、data、config与$http的参数一致,
  下面有一个simple demo用于展示如何使用$http()及$http.post()。
&!DOCTYPE HTML&
&html lang="zh-cn" &
&meta charset="UTF-8"&
&title&CSSClasses&/title&
&script src="angular.min.js" type="text/javascript"&&/script&
&script type="text/javascript"&
function ctrl($http,$scope){
$scope.login = function(user){
$http.post("login.do",user).success(function(data, status, headers, config){
alert("success");
}).error(function(data, status, headers, config){
alert("error");
$scope.login1 = function(user){
$http({url:"login.do",data:user}).success(function(data, status, headers, config){
alert("success");
}).error(function(data, status, headers, config){
alert("error");
&body ng-app&
&div ng-controller="ctrl"&
&form name="loginFm"&
Name:&input ng-model="user.name" /&
pwd: &input ng-model="user.pwd" /&
&input type="button" value="login" ng-click="login(user)" /&
&input type="button" value="login1" ng-click="login1(user)" /&- JavaScript Developer and Blogger
Published: Wed Aug 05 2015
The Angular team has just announced that the convenience wrappers success and error for promise handling have been deprecated. This is not surprising as the success/error API is not only non standard, but might also lead to unexpected results. In this post I will highlight some of the potential pitfalls from using success.
One of the major advantages of promises is the ability to flatten and chain potentially complex sequences of ajax calls. Not only does this help us simplify code, but more importantly, it helps us manage timing and dependencies through a sequence of calls.
So how does success fall short here?
Simple calls with no chaining is usually no problem, but if you try to chain off a success handler you might be in for a surprise. The fundamental difference between 'success' and 'then' is that success will return the original promise instead of returning a new derived promise. Each then() invocation returns a fresh promise – which is key to chaining multiple promise calls.
It's not that success doesn't allow chaining – it does, but a side effect of returning the original promise is that all chained success handlers will fire during the same cycle. This means that if you return a promise from a success handler, the next success handler will fire before the newly returned promise resolves.
Below is an example of two service calls where the second call is not picked up by the second success handlers since both success handlers are tied to the initial promise.
$http.get('/firstUrl')
.success(function(response){
console.log(response);
//This promise is returned in vain - no one cares about the result :-(
return $http.get('/secondUrl')
.success(function(response){
console.log('I only have access to the data from the first call');
console.log(response);
If we were to rewrite this using then handlers instead – we would get the following:
$http.get('/first/Url')
.then(function(response){
console.log('first then');
console.log(response.data);
//Someone actually cares about the result now :-)
return $http.get('/secondUrl');
.then(function(response){
console.log('I am enjoying the results from the second call');
console.log(response.data);
The key difference here is that each then call will wait for the current promise to resolve before executing.
Obviously it's possible to rewrite the success handler example to get access to the second call, but the code is far from pretty.
See below:
$http.get('/firstUrl')
.success(function(response){
console.log('first success');
console.log(response);
return $http.get('/secondUrl').success(function(res){
console.log('nested handler');
console.log(res);
.success(function(response){
console.log('Fires before the nested success handler. Still only sees the first result though');
console.log(response);
This is actually pretty ugly and probably negates all the benefits of flattening promise chains. In fact, this is only slightly better than skipping promises altogether and going with straight callbacks.
I am not sure why success was added to begin with, but I guess it adds a slight convenience by flattening the response object by getting rid of the .data property on the original response object. However, we can easily take care of this using then handlers by chaining on an extra then handler like so:
$http.get('/someUrl')
.then(function(response){
return response.//this flattens the response by removing .data
.then(function(response){
console.log(response);//same as response.data from above
If you liked this article, share it with your friends on social media:
We also have a new
about advanced Angular topics.
I invite you to follow me on twitterAngularJS中$http使用的简单介绍
作者:EldonZhao
字体:[ ] 类型:转载 时间:
在AngularJS中主要使用$http服务与远程http服务器交互,本篇文章主要介绍了AngularJS中$http使用的简单介绍,非常具有实用价值,需要的朋友可以参考下。
在AngularJS中主要使用$http服务与远程http服务器交互,其作用类似于jquery中的$.ajax服务:
$http是AngularJS的一个核心服务,利用浏览器的xmlhttprequest或者via JSONP对象与远程HTTP服务器进行交互;
与$.ajax相同,支持多种method请求:get、post、put、delete等;
controller中可通过与$scope同样的方式获取$http对象,形如:function controller($ http, $ scope){};
$http使用说明:
$http服务使用如下面代码所示:
// 1.5以下版本
$http(config)
.success(function(data, status, headers, config){//请求成功执行代码})
.error(function(data, status, headers, config){//请求失败执行代码})
// 1.5以上版本
$http(config).then(
function successCallback(response){//请求成功执行代码},
function errorCallback(response){//请求失败执行代码}
具体参数、方法说明:
配置参数:
config是请求的配置参数总集,格式为json;
包含的配置项包括:
method:字符串类型,请求方式如"GET","POST","DELETE"等;
url:字符串类型,请求的url地址;
params:json类型,请求参数,将在url上被拼接成?key=value的形式;
data:json类型,请求数据,将放在请求内发送至服务器;
cache:bool类型,true表示http GET请求时采用默认的$http cache,否则使用$cacheFactory的实例;
timeout:整数类型,超时时间;
回调函数:
success是请求成功后的回调函数;
error是请求失败后的回调函数;
data是响应体;
status是相应的状态值;
headers是获取getter的函数;
config是请求中的config json对象;
method属性可以作为config配置参数中的一个属性,也可以直接作为方法调用,如:
$http.post(url, data, config)
$http使用范例:
var searchOplog = function ($http, table, btn) {
url: 'data/oplog.json',
method: 'GET'
}).then(function successCallback(response) {
console.log('get Oplog success:', response);
table.init(response.data);
btn.button('reset');
btn.dequeue();
}, function errorCallback(response) {
console.log('errorCallback Response is:', response);
table.init();
btn.button('reset');
btn.dequeue();
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
您可能感兴趣的文章:
大家感兴趣的内容
12345678910
最近更新的内容
常用在线小工具问题对人有帮助,内容完整,我也想知道答案
问题没有实际价值,缺少关键内容,没有改进余地
这两个感觉都差不多啊,官方文档说angular1.5之后废弃了success和error改用then,我现在还一直在用success和error..
答案对人有帮助,有参考价值
答案没帮助,是错误的答案,答非所问
要将区别先弄清$http服务,它是对原生XMLHttpRequest对象的简单封装,是只能接受一个参数的方法,这个方法会返回一个promise对象,具有sccess和error两个方法。当然,我们也可以在响应返回时用then方法来处理,会得到一个特殊的参数,代表了对象的成功或失败信息,或者可以使用success和error回调代替。
这样就很明晰了,then方法和success方法的主要区别就是,then方法会接受到完整的响应对象,而success则会对响应对象进行析构。
答案对人有帮助,有参考价值
答案没帮助,是错误的答案,答非所问
then是源于Promise对象的语法.是异步编程的一种解决方案,比传统的回调函数更合理和更强大切更利于阅读.
success就是典型的回调嵌套.你现在可以能的一两层回调没什么.你想象一下如果嵌套5个以上回调是什么样子,性能方面暂且不说,就连看都看得迷迷糊糊then就清晰很多 切性能较好
你可以看一下
同步到新浪微博
分享到微博?
你好!看起来你挺喜欢这个内容,但是你还没有注册帐号。 当你创建了帐号,我们能准确地追踪你关注的问题,在有新答案或内容的时候收到网页和邮件通知。还能直接向作者咨询更多细节。如果上面的内容有帮助,记得点赞 (????)? 表示感谢。
明天提醒我
关闭理由:
删除理由:
忽略理由:
推广(招聘、广告、SEO 等)方面的内容
与已有问题重复(请编辑该提问指向已有相同问题)
答非所问,不符合答题要求
宜作评论而非答案
带有人身攻击、辱骂、仇恨等违反条款的内容
无法获得确切结果的问题
非开发直接相关的问题
非技术提问的讨论型问题
其他原因(请补充说明)
我要该,理由是:对比分析AngularJS中的$http.post与jQuery.post的区别
投稿:hebedich
字体:[ ] 类型:转载 时间:
这篇文章主要给大家对比分析AngularJS中的$http.post与jQuery.post的区别,十分的详细,是篇非常不错的文章,这里推荐给小伙伴们。
很多时候我们需要用ajax提交post数据,angularjs与jq类似,也有封装好的post。
但是jQuery的post明显比angularjs的要简单一些,人性化一些。
AngularJS:
$http.post('do-submit.php',myData)
.success(function(){
&&& // some code
$.post('do-submit.php', myData, function() {
&&& // some code
看起来没什么区别吧?可是,用angularjs的$http提交的数据,在php服务器端却无法通过$_REQUEST/$_POST获取到,而需要用:
$params = json_decode(file_get_contents('php://input'),true);
来获取。什么原因呢?
这是因为两者的post对header的处理有所不同……jQuery会把作为JSON对象的myData序列化,例如:
var myData = { a : 1, b : 2 };
// jQuery在post数据之前会把myData转换成字符串:"a=1&b=2"
而Angular不会。
解决方案是什么?
1.引入jquery,前提是目标用户不介意多加载一个几十K的脚本。(不推荐)
2.在服务器端(PHP)通过& $params = json_decode(file_get_contents('php://input'),true);&& 获取参数,小项目可以,大项目要一个一个改。(不推荐)
3.修改Angular的$httpProvider的默认处理:& (为了便于以后的管理,这是最好的办法)
小伙伴们是否对AngularJS中的$http.post与jQuery.post的区别有了进一步的认识了呢,希望大家读完本文能够有所得。
您可能感兴趣的文章:
大家感兴趣的内容
12345678910
最近更新的内容
常用在线小工具

我要回帖

更多关于 http success error 的文章

 

随机推荐