Beh*_*ooz 9 angularjs angular-promise
由于AngularJS中的success()和error()函数已弃用,我正在更新我的代码,将其替换为then().现在根据我的理解,这两段代码的行为应该相同:
$http
.get(/* some params */)
.success(function() {
// success cases here
})
.error(function() {
// error cases here
});
Run Code Online (Sandbox Code Playgroud)
和
$http
.get(/* some params */)
.then(function() {
// success cases here
}, function() {
// error cases here
});
Run Code Online (Sandbox Code Playgroud)
但在某些情况下,我会得到不同的行为.你能否向我解释为什么会发生这种情况,更重要的是,保证使用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
});
Run Code Online (Sandbox Code Playgroud)
另一方面,.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);
});
Run Code Online (Sandbox Code Playgroud)
另请注意,该$http服务在调用提供给和方法的函数时提供了四个参数 .(data, status, headers, config).success.error
该$q服务仅为提供给或方法的函数提供一个参数(响应).对于由服务创建的promises ,响应对象具有以下属性:1.then.catch$http
链接承诺
因为调用
thenpromise 的方法会返回一个新的派生promise,所以很容易创建一个promise链.可以创建任何长度的链,并且由于可以使用另一个承诺(将进一步推迟其解析)来解决承诺,因此可以在链中的任何点暂停/推迟承诺的解析.这使得实现强大的API成为可能.2
这些.success和.error方法已被弃用并从AngularJS V1.6中删除.
有关更多信息,请参阅
| 归档时间: |
|
| 查看次数: |
4502 次 |
| 最近记录: |