可以将.catch()
链接在Angular中吗?实施例
$http
.get('/foo')
.catch(function() {})
// can I chain here?
答案 0 :(得分:1)
是
$http
.get('/foo')
.then(function() {
console.log('THEN #1')
})
.catch(function() {
console.log('CATCH');
return 'foo';
})
.then(function(val) {
console.log('THEN #2');
console.log('val: ', val);
})
;
此日志:
CATCH
THEN #2
val: foo
作为NewDev mentions,.catch()
的返回值在第二个.then()
中可用。
angular
.module('app', [])
.controller('MainController', MainController)
;
function MainController($http) {
$http
.get('/foo')
.then(function() {
console.log('THEN #1')
})
.catch(function() {
console.log('CATCH');
return 'foo';
})
.then(function(val) {
console.log('THEN #2');
console.log('val: ', val);
})
;
}

<!DOCTYPE html>
<html ng-app='app'>
<head>
<script data-require="angular.js@1.4.6" data-semver="1.4.6" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div ng-controller='MainController as vm'>
<p>test</p>
</div>
</body>
</html>
&#13;