2016-08-07 90 views
4

我已經向我的路由器添加了授權管道步驟。一切正常,但是當我使用Redirect類將用戶指向登錄頁面時,它將URL作爲其參數。如果我使用Router.navigateToRoute(),我寧願傳入路由名稱。這可能嗎?使用Aurelia重定向類

@inject(AuthService) 
class AuthorizeStep { 
    constructor (authService) { 
     this.authService = authService; 
    } 

    run (navigationInstruction, next) { 
     if (navigationInstruction.getAllInstructions().some(i => i.config.auth)) { 
      if (!this.authService.isLoggedIn) { 
       return next.cancel(new Redirect('url-to-login-page')); // Would prefer to use the name of route; 'login', instead. 
      } 
     } 

     return next(); 
    } 
} 

回答

7

一些谷歌搜索後,我發現了Router.generate()方法,它需要一個路由器名稱(和可選PARAMS),並返回URL。現在我已經更新了我的授權步驟如下:

@inject(Router, AuthService) 
class AuthorizeStep { 
    constructor (router, authService) { 
     this.router = router; 
     this.authService = authService; 
    } 

    run (navigationInstruction, next) { 
     if (navigationInstruction.getAllInstructions().some(i => i.config.auth)) { 
      if (!this.authService.isLoggedIn) { 
       return next.cancel(new Redirect(this.router.generate('login'))); 
      } 
     } 

     return next(); 
    } 
} 

編輯:多一些谷歌搜索後,我發現了RedirectToRoute類;

import { RedirectToRoute } from 'aurelia-router'; 

...

return next.cancel(new RedirectToRoute('login'));