Angular 2 relative authguard redirects

Is there a way to redirect with a relative path pattern in authguard?

I tried it with

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

which should redirect from /projects/2/servers/71 to /projects/2/servers/ , but it always redirects it to /servers (When I do the same in the component, it works fine).

+5
source share
2 answers

I worked around this with a little helper function. But this only works if you know the URL scheme.

 /** * ATTENTION: RECURSIVE * * We are searching for the url "searchString" which comes before * the parameter we are really search. * Eg 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); } 

Using

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

relativeTo should also accept ActivatedRouteSnapshot , it looks like it might have been missed, meanwhile a workaround:

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

Source: https://habr.com/ru/post/1264152/


All Articles