可以将.catch链接在Angular中吗?

时间:2015-10-09 22:44:52

标签: angularjs angular-promise

可以将.catch()链接在Angular中吗?实施例

$http
  .get('/foo')
  .catch(function() {})
  // can I chain here?

1 个答案:

答案 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;
&#13;
&#13;