在下面的代码中 router.createUrlTree 使用了绝对地址
export class AuthorizeGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean | UrlTree {
return this.authService.isAuthenticated() ?
true :
this.router.createUrlTree(
["https://account.cnblogs.com/signin"],
{ queryParams: { returnUrl: state.url } }
);
}
}
运行时却报错
Cannot match any routes. URL Segment: 'https:/account.cnblogs.com/signin'`
请问如何解决?
实际要解决的问题是在 guard 中跳转到外部地址(redirect to external url)
UrlTree 只支持相对地址,通过下面的代码解决了
export class AuthorizeGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean {
if(this.authService.isAuthenticated()) {
return true;
} else {
const path = this.router.createUrlTree(
["signin"],
{ queryParams: { returnUrl: location.origin + state.url } }
).toString();
location.href = "https://account.cnblogs.com" + path;
return false;
}
}
}