作为success()
和error()
AngularJS 中已弃用函数,我正在更新我的代码,将它们替换为 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, status, headers, 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
服务在调用提供给的函数时提供四个参数 (data, status, headers, config)
.success
和 .error
方法。
$q
服务仅向 .then
或 .catch< 提供的函数提供一个参数(响应)/
方法。对于 $http
服务创建的 Promise,响应对象具有以下属性: 1
- data – {string|Object} – 使用转换函数转换的响应正文。
- status – {number} – 响应的 HTTP 状态代码。
- headers – {function([headerName])} – header 获取函数。
- 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.2
更新
.success
和 .error
方法已被弃用并从 AngularJS V1.6 中删除。
欲了解更多信息,请参阅
关于AngularJS then() 的行为与 success()-error() 不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35415659/