cra*_*bus 5 angular2-routing angular
有没有办法在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;
}
}
Run Code Online (Sandbox Code Playgroud)
它应该重定向/projects/2/servers/71到/projects/2/servers/但它总是将其重定向到/servers(当我在一个组件中做同样的工作时它工作正常).
我用一个小辅助函数解决了这个问题。但这仅在您知道 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);
}
Run Code Online (Sandbox Code Playgroud)
用法:
this._router.navigate([
'projects',
getUrlParameterByChild('servers', route),
'servers'
])
Run Code Online (Sandbox Code Playgroud)