Kas*_*yap 5 url typescript angular
我有page1和page2。我在page2路由上添加了canActivate gaurd,想知道我是否来自page1?我怎么做?
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
//If from Page 1 { clearCache() }
return true;
}
Run Code Online (Sandbox Code Playgroud)
提前致谢。
首先这样做:它会给你一个 URL:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
console.log(state.url);
}
Run Code Online (Sandbox Code Playgroud)
如果您想将用户重定向到他/她来自的网址,您可以这样做:有关信息,请阅读TEACH AUTHGUARD TO AUTHENTICATE部分下的官方教程文档。
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
let url: string = state.url;
return this.checkLogin(url);
}
checkLogin(url: string): boolean {
if (this.authService.isLoggedIn) { return true; }
// Store the attempted URL for redirecting
this.authService.redirectUrl = url;
// Navigate to the login page with extras
this.router.navigate(['/login']);
return false;
}
Run Code Online (Sandbox Code Playgroud)
小智 9
我也试图找到这个问题的答案,终于找到了。在你的守卫类的构造函数中,你需要(私有路由器:路由器);然后在你的 canActivate 守卫中,你可以使用 this.router.url 来检查你来自的 URL:
export class StatusGuard implements CanActivate {
constructor(private router: Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
console.log(`route ${route.url}`); // the url you are going to
console.log(`state ${state.url}`); // the url you are going to
console.log(`router ${this.router.url}`); // the url you are coming from
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2637 次 |
| 最近记录: |