Angular 2 authguard相对重定向

时间:2017-02-13 09:37:12

标签: angular angular2-routing

有没有办法在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(当我在组件中执行相同操作时,它可以正常工作)。

2 个答案:

答案 0 :(得分: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;
      // }


}

答案 1 :(得分:0)

我用一个小帮手功能解决了这个问题。但这只有在您知道网址架构的情况下才有效。

onStop

<强>用法

/**
 * 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);
}