2017-07-18 49 views
1

我要取消我在錯誤的登錄的情況下的路線,這是我ANGULARJS NG-ROUTE代碼:AngularJs:取消路線的決心沒有承諾

monApp.config(function ($routeProvider, $locationProvider){ 

    var rsf = { // This function tells if user is logged or not 
     "check":function(stockeUtilisateur,$location,Notification){ 
      u = stockeUtilisateur.getUtilisateur(); 

       if(u.role=='admin'||u.role=='utilisateur'){ 
        Notification.success("Youre logged"); 
       } 
       else{ 
        $location.path('/accueil');  //redirect user to home. 
        Notification.error("bad password"); 
       } 
     } 
    }; 

    $routeProvider 
    .when('/accueil', { 
     templateUrl: 'vues/accueil.html', 
     controller: 'neutreCtrl' 
    }) 
    .when('/compte', { 
     templateUrl: 'vues/compte.html', 
     controller: 'compteCtrl', 
     resolve:rsf 
    }) 

    .otherwise({redirectTo: '/accueil'}); 
}) 

的問題是,我不希望在登錄失敗的情況下使用$location.path(),因爲它重新加載整個頁面,而我只需要留在路由上,只要用戶登錄錯誤就取消路由。

我不知道我可以使用什麼代碼,我試過這個而不是$location.path()event.preventDefault();但它不起作用。

我也試過resolve.cancel();但它不工作,嗅探!

如果我刪除$location.path(),那麼該解決方案仍然有效,我可以在用戶沒有登錄時看到「compte」視圖。

換句話說,我不想重定向,但我想決心在密碼錯誤的情況下不做任何事情。

也許你有想法嗎?

謝謝。

+0

我沒有足夠的信心發佈答案,但快速研究表明,在$ locationChangeStart事件中使用防止默認值。 https://weblogs.asp.net/dwahlin/cancelling-route-navigation-in-angularjs https://stackoverflow.com/questions/16344223/angularjs-cancel-route-change-event –

+1

我會迴應@Jordan。 JD表示,利用路由器事件。您很可能必須暫時存儲登錄信息*某個地方**以便在事件處理程序中檢查它。但請務必刪除該數據,而不管登錄成功/失敗。 – jusopi

回答

0

問題是,我不想在登錄失敗的情況下使用$ location.path(),因爲它重新加載整個頁面,而我只需要留在路線上,並簡單地取消路線,只要用戶登錄錯誤。

要取消從分解器功能的路由改變,使用throw statement

monApp.config(function ($routeProvider, $locationProvider){ 

    var rsf = { // This function tells if user is logged or not 
     "check":function(stockeUtilisateur,$location,Notification){ 
      u = stockeUtilisateur.getUtilisateur(); 

       if(u.role=='admin'||u.role=='utilisateur'){ 
        Notification.success("Youre logged"); 
       } 
       else{ 
        //$location.path('/accueil'); 
        //Notification.error("bad password"); 
        throw "bad bassword"; 
       } 
     } 
    }; 

    $routeProvider 
    .when('/accueil', { 
     templateUrl: 'vues/accueil.html', 
     controller: 'neutreCtrl' 
    }) 
    .when('/compte', { 
     templateUrl: 'vues/compte.html', 
     controller: 'compteCtrl', 
     resolve:rsf 
    }) 

    .otherwise({redirectTo: '/accueil'}); 
}) 

當分解器功能拋出一個錯誤,防止了路由改變和$routeChangeError event被廣播。

+0

它的工作原理!你太棒了,非常感謝你! – jojo45