由于在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()函数保证相同行为的方法是什么?
因此它们不适合链接.
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} – 使用转换函数转换的响应体.
> status – {number} – 响应的HTTP状态代码.
> headers – {function([headerName])} – 标头getter函数.
> config – {Object} – 用于生成请求的配置对象.
> statusText – {string} – 响应的HTTP状态文本.
Chaining promises
Because calling the
then
method of a promise returns a new derived promise,it is easily possible to create a chain of promises. It is possible to create chains of any length and since a promise can be resolved with another promise (which will defer its resolution further),it is possible to pause/defer resolution of the promises at any point in the chain. This makes it possible to implement powerful APIs.07001
更新
.enccess和.error方法已被弃用并从AngularJS V1.6中删除.
有关更多信息,请参阅
> Why are angular $http success/error methods deprecated? Removed from v1.6?