如何在角度2的canActivate防护中获取用户尝试打开的路线?
如何让守卫观察每个路线参数变化,例如:在路线中改变身份?
import { Injectable } from '@angular/core';
import {Observable, Observer, Subject} from "rxjs/Rx";
@Injectable()
export class RightsGuard implements CanActivate {
constructor(
private router: Router,
private route: ActivatedRoute
// private state: RouterStateSnapshot
) { }
canActivate(): Observable<boolean> | boolean {
var targetUrl = ???
// var targetUrl = this.router.url // is showing previous url?
return true;
}
}
Angular 2 get current route in guard使用private state: RouterStateSnapshot
的建议答案
然后this.route.url
对我不起作用,因为它会引发DI错误:
Error: Uncaught (in promise): Error: DI Error
Error: DI Error
答案 0 :(得分:3)
以下似乎有效,但是不能在构造函数中注入路由和状态,因为这会导致错误。
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
console.log("route-access",state);
}
然而,这导致了每个路线仅调用一次保护的问题。对于路由参数的更改,例如:id,不调用guard。但这似乎与3.2路由器中的错误相关: