2017-08-25 61 views
0

我们使用的是AngularJS 1.6,并且已经编写了下面的指令来提交表单。Angular指令中的捕获异常

(function() { 
    "use strict"; 

    function formSubmitDirective(cookieService) { 
     return { 
      require: "form", 
      link: function ($scope, $el) { 
       var csrf = cookieService.csrfTokenCookie(); 
       $el[0].querySelector('#csrf').value = csrf; 
       $el[0].submit(); 
      } 
     }; 
    } 

    formSubmitDirective.$inject = ['cookieService']; 

    angular 
     .module('csmDirectives') 
     .directive('csmFormSubmit', formSubmitDirective); 

}()); 

在这里,我们使用它:

<div ng-if="vm.autoLogout"> 
    <form csm-form-submit role="form" action="/app/logout" method="POST"> 
     <input type="hidden" id="csrf" name="_csrf" ng-value="vm.csrfToken"/> 
    </form> 
</div> 

的问题是,应用程序有时POST请求时产生403错误。在这种情况下,我想捕获该异常并希望将页面移动到以下网址:

localhost:8080/app/index.html#timeout 

有没有办法做到这一点?

回答

0

你可以改变你的电话提交:

link: function ($scope, $el) { 
    var csrf = cookieService.csrfTokenCookie(); 
    $el[0].querySelector('#csrf').value = csrf; 
    try { 
    $el[0].submit(); 
    } catch(e) { 
    // You would have to define a timeout-state 'state', assuming you're 
    // using states though; 
    state.go('timeout-state'); 
    } 
}, 
controller: function($state, $stateParams) { 
    var scope = this; 
    scope.state = $state; 
} 

我没有测试过这一点,但你需要的控制器那里获取$状态。所有这些都假设你使用某种$ state(可能是$ routeProvider),但是如果你使用的是Angular1.6,那么这是一个很好的选择。

+0

它看起来像是一个真正的表单发布,所以我不知道你可以捕获这样的错误 –