AngularJS then()的行为与success()不同 – error()
参见英文答案 >
Why are AngularJS $http success/error methods deprecated? Removed from v1.6?2个
由于在AngularJS中不推荐使用success()和error()函数,我正在更新我的代码,用then()替换它们.现在根据我的理解,这两段代码的行为应该相同: $http .get(/* some params */) .success(function() { // success cases here }) .error(function() { // error cases here }); 和 $http .get(/* some params */) .then(function() { // success cases here },function() { // error cases here }); 但在某些情况下,我会得到不同的行为.你能否向我解释为什么会发生这种情况,更重要的是,使用then()函数保证相同行为的方法是什么?
.success和.error方法忽略返回值.
因此它们不适合链接. var httpPromise = $http .get(/* some params */) .success(function onSuccess(data,status,headers,config) { var modifiedData = doModify(data); //return value ignored return modifiedData; }) .error(function onError(data,config) { // error cases here }); httpPromise.then(function onFullfilled(response) { //chained data lost //instead there is a response object console.log(response.data); //original data console.log(response.status); //original status }); 另一方面,.then和.catch方法返回一个派生的promise,适用于从返回(或抛出)值或新promise中链接. var derivedPromise = $http .get(/* some params */) .then(function onFulfilled(response) { console.log(response.data); //original data console.log(response.status); //original status var modifiedData = doModify(response.data); //return a value for chaining return modifiedData; }) .catch(function onRejected(response) { // error cases here }); derivedPromise.then(function onFullfilled(modifiedData) { //data from chaining console.log(modifiedData); }); 响应对象与四个参数 另请注意,$http服务在调用提供给.success和.error方法的函数时提供了四个参数(data,config). $q服务仅为提供给.then或.catch方法的函数提供一个参数(响应).对于由$http服务创建的promises,响应对象具有以下属性:1 > data – {string | Object} – 使用转换函数转换的响应体.
更新 .enccess和.error方法已被弃用并从AngularJS V1.6中删除. 有关更多信息,请参阅 > Why are angular $http success/error methods deprecated? Removed from v1.6? (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |