2017-02-13 45 views
5

有没有办法在authguard中使用相对路径模式进行重定向?Angular 2 authguard相对重定向

@Injectable() 
export class ServerAuthGuard implements CanActivate { 
    constructor(private _router: Router, 
       private _route: ActivatedRoute) { 
    } 

    canActivate(route: ActivatedRouteSnapshot): boolean { 
     this._router.navigate(['../../servers/'], {relativeTo: this._route}); 

     return false; 
    } 
} 

尝试它应该从/projects/2/servers/71重定向到/projects/2/servers/但它总是重定向到/servers(当我做相同的,它工作正常的组件)。

+0

什么途径是'this._route'指向? –

+0

确定它指向“”。所以我明白为什么我要重定向到'/ servers'。当我用ActivatedRouteSnapshot尝试它时,我得到一个'{relativeTo:ActivatedRouteSnapshot; }'不能分配给类型为'NavigationExtras''的参数 – crashbus

+1

对不起,不知道。你为什么不使用绝对路径? –

回答

0

我工作围绕这一个小助手功能。但是这只有在你知道url的模式时才有效。

/** 
* ATTENTION: RECURSIVE 
* 
* We are searching for the url "searchString" which comes before 
* the parameter we are really search. 
* E.g. if you have a url like "projects/:projectId/servers/:serverId 
* and you need the :projectId your 'searchString' is 'servers' 
*/ 
function getUrlParameterByChild(searchString: string, 
           route: ActivatedRouteSnapshot, 
           next: boolean = false): string { 
    let url: string = route.url[0] ? route.url[0].path : ''; 

    if (!url && !route.parent) { 
     throw new Error('Parameter not found in url'); 
    } 

    if (next) { 
     return url; 
    } 

    return getUrlParameterByChild(searchString, route.parent, url === searchString); 
} 

使用

this._router.navigate([ 
    'projects', 
    getUrlParameterByChild('servers', route), 
    'servers' 
]) 
0

对于relativeTo也应该接受ActivatedRouteSnapshot,看起来这可能被忽视,在此期间,这里是一个解决办法:

canActivate(
    next: ActivatedRouteSnapshot, 
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean { 
     // if(...) { 
     const segments = state.url.split('/'); 
     segments.pop(); 
     segments.shift(); 
     this.router.navigate(segments); 
     // } else { 
     // return true; 
     // } 


}