2017-08-25 48 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

它看起來像是一個真正的表單發佈,所以我不知道你可以捕獲這樣的錯誤 –