Zer*_*ool 5 angularjs angularjs-directive angular2-template angular2-routing angular
我正在尝试创建CanDeactivate防护,以在用户离开路线时提示“保存更改”。有一些我想排除的路线(可以说,当用户切换选项卡,但不选择新项目时)。我一直在努力了解如何在不使用某种导航服务的情况下获取目标URL,而只保留完整的URL。这是我的签名,可以取消激活
// This is what handles the deactivate
public canDeactivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
Run Code Online (Sandbox Code Playgroud)
所有的“ route”和“ state”对象都包含先前的URL,而没有有关目标URL的信息。
我触发另一个组件中的导航
this._router.navigate(['/clients', this.selectedClient.id, page]);
Run Code Online (Sandbox Code Playgroud)
小智 6
实际上,目标状态是CanDeactivate的参数之一。
canDeactivate(
component: CanComponentDeactivate,
route: ActivatedRouteSnapshot,
currentState: RouterStateSnapshot,
nextState: RouterStateSnapshot
): Observable<boolean>|Promise<boolean>|boolean {
return true;
}
Run Code Online (Sandbox Code Playgroud)
参考:https : //angular.io/api/router/CanDeactivate
您可以订阅路由器的事件:
NavigationStart应该在 CanDeactivate 之前触发,这样你就可以抓住目的地。
routingDestination: string = "";
constructor(router:Router) {
router
.events
.filter(e:Event => e instanceof NavigationStart)
.subscribe((e: NavigationStart) => this.routingDestination = e.url)
}
}
Run Code Online (Sandbox Code Playgroud)
除此之外,我认为需要知道目的地CanDeactivate是一种设计缺陷。但由于我不知道你的应用程序,这实际上可能是正确的方法。