有没有办法强制路由器导航到同一路由,以便通过调用此canActivate防护两次来更新路由数据:
@Injectable()
export class LevelGuard implements CanActivate {
private user_query_: string;
private level_query_: string;
constructor(private router_: Router, private query_resolver_: QueryResolver) { };
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
let user: string = route.params["user"];
let level: string = route.params["level"];
if (!user && !level) { //=> "/create"
this.query_resolver_.setQuery({ user: this.user_query_ || "none", level: this.level_query_ || "none" });
this.level_query_ = "";
this.user_query_ = "";
return true;
}
else if (user && !level) { //=> "/create/:user"
this.router_.navigate(["/create"]);
this.level_query_ = "none";
this.user_query_ = user;
return false;
}
else { //=> "/create/:user/:level"
this.router_.navigate(["/create"]);
this.level_query_ = level;
this.user_query_ = user;
return false;
}
};
}
如果路由已经是“/ create”,那么当这个canActivate守护重定向到“/ create”时,它应该为“/ create /:user”和“/ create /:user /:level”执行,后卫不是第二次被召唤。有一个更复杂的路由方案,可以避免这个问题,但这会大大简化它。
编辑:解决这个问题的一种方法是添加一个虚拟组件,然后导航到“/ create”,但它会导致明显的转换,组件不会被重用。
this.router_.navigate(["/redirect"]).then((nav) => {
this.router_.navigate(["/create"]);
});
答案 0 :(得分:0)
canActivate
不适合儿童路线。
您需要使用canActivateChild
并在路由器上设置它:
<强>路由器强>
{
path: '/create',
loadChildren: 'yourModule#YourModule',
canLoad: [LevelGuard ],
canActivateChild: [LevelGuard ]
},
<强>保护强>
只需添加LevelGuard
:
canActivateChild() {
// your code here
}
答案 1 :(得分:0)
这就是我最终要做的事情,因为“重定向”导致了NavigationCancel事件,我订阅了Router.events并跟踪最后一个导航是否有NavigationEnd或NavigationCancel。尝试使用布尔标志,但无法找到在正确的时间将标志重置为false的方法。
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
let mode = route.url[0].path as "create" | "play";
let user: string = route.params["user"];
let level: string = route.params["level"];
if (!user && !level) { //=> "/mode"
if (this.last_navigation_outcome instanceof NavigationCancel) {
return Observable.of(true);
}
else {
user = this.user_identity_.id;
let query = { mode, user, level: "none" };
this.query_resolver_.setQuery(query);
return this.level_resolver_.resolveLevel(query).map((level) => {
return true;
});
}
}
else if (user && !level) { //=> "/mode/:user"
let query = { mode, user, level: "none" };
this.query_resolver_.setQuery(query);
return this.level_resolver_.resolveLevel(query).map((level) => {
this.router_.navigate(["/" + mode]);
return false;
});
}
else { //=> "/mode/:user/:level"
let query = { mode, user, level };
this.query_resolver_.setQuery(query);
return this.level_resolver_.resolveLevel(query).map((level) => {
this.router_.navigate(["/" + mode]);
return false;
});
}
};