2017-02-13 18 views
5

Có cách nào để chuyển hướng với mẫu đường dẫn tương đối trong trình bảo vệ không?Góc 2 authguard chuyển hướng tương đối

Tôi đã thử nó với

@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; 
    } 
} 

mà nên chuyển hướng từ /projects/2/servers/71 để /projects/2/servers/ nhưng Nó luôn luôn chuyển hướng nó vào /servers (Khi tôi làm như vậy trong một thành phần nó hoạt động tốt).

+0

đường gì là 'this._route' trỏ đến? –

+0

Ok nó trỏ đến "". Vì vậy, nó có ý nghĩa tại sao tôi nhận được chuyển hướng đến '/ servers'. Khi tôi thử nó với ActivatedRouteSnapshot, tôi nhận được một 'Tham số kiểu '{relativeTo: ActivatedRouteSnapshot; } 'không thể gán cho tham số kiểu' NavigationExtras'' – crashbus

+1

Xin lỗi, không biết. Tại sao bạn không sử dụng đường dẫn tuyệt đối? –

Trả lời

0

tôi làm việc xung quanh này với một hàm helper ít. Nhưng điều này chỉ hoạt động nếu bạn biết lược đồ của 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); 
} 

Cách sử dụng:

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

relativeTo cũng nên chấp nhận một ActivatedRouteSnapshot, trông như thế này có thể đã bị bỏ qua, trong khi chờ đợi ở đây là một cách giải quyết:

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


} 
Các vấn đề liên quan